Atlaslog
Atlaslog / Field Notes / Loading & display
Field note · Loading & display

CSV longitude and latitude columns swapped, points land off Somalia

Quick answer

The CSV header was name,lat,lng but the code read by column index, so 116.4 became a latitude and 39.9 became a longitude. Longitudes above 90 are silently dropped by Leaflet, which is why the points vanish instead of appearing in the Indian Ocean.

Last verified 2026-11-03 · Multiple versions · Cite this page
Applies to: PapaParse 5.4 · Leaflet 1.9.x · turf.js 7.x
Symptom
Checklist
  1. Print the raw first line and confirm the header order matches the data order.
  2. Check whether the code reads by column name or by index; index-based access must become name-based.
  3. Compute the maximum absolute value of the latitude column before loading; above 90 means swapped or bad data.
  4. Plot the first point alone and see whether it lands in Beijing or the Indian Ocean.
  5. Remember the order differs: GeoJSON is [lng, lat], L.latLng is (lat, lng).
Fix

Parse with header: true and read row.lng and row.lat by name, then validate ranges before constructing points; if the pair is already swapped, exchange it once and keep one convention through the whole pipeline.

Code
const pts = rows.map(r => [r[1], r[2]]);   // 实际拿到的是 [116.397428, 39.909230]
// -> Leaflet 认为纬度 116.397428,超限,点被丢弃
const { data } = Papa.parse(text, { header: true, skipEmptyLines: true });

const points = data.map((r, i) => {
  const lat = Number(r.lat ?? r.latitude);
  const lng = Number(r.lng ?? r.lon ?? r.longitude);
  if (!Number.isFinite(lat) || Math.abs(lat) > 90)
    throw new Error(`第 ${i + 2} 行纬度非法:${r.lat}`);
  if (!Number.isFinite(lng) || Math.abs(lng) > 180)
    throw new Error(`第 ${i + 2} 行经度非法:${r.lng}`);
  return { name: r.name, lat, lng };
});

L.geoJSON(points.map(p => ({
  type: 'Feature',
  properties: { name: p.name },
  geometry: { type: 'Point', coordinates: [p.lng, p.lat] }   // GeoJSON 永远是经度在前
})), {
  pointToLayer: (f, ll) => L.circleMarker(ll, { radius: 4 })
}).addTo(map);
Watch out
All 120 field notesChinese originalRunnable examples
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Cite this page

Atlaslog (2026). CSV longitude and latitude columns swapped, points land off Somalia. https://www.jingweizhi.com/en/cookbook/csv-lonlat-swapped.html (accessed 2026-11-03).