Search code examples
javascriptleafletproj4jsepsg

Proj4Leaflet transform from 4326 to 3857 in Leaflet


I am working on Leaflet from last week and this issue is killing me.

The database returns coordinates to create a Leaflet marker (working with default Map.CRS EPSG3857), so I decide to transform the dataBase coordinates 4326 to 3857 with proj4js:

var iarCoordinate = [-76.495207812, 3.429960207],
    obSource = new proj4.Proj('EPSG:4326'),
    obDest = new proj4.Proj('EPSG:3857'),        
    obResult = new proj4.Point(iarCoordinate);
proj4.transform(obSource, obDest, obResult);
//obResult = [-8515407.581757482, 382049.6844491562]

These [-8515407.581757482, 382049.6844491562] do not represents the correct point.

If I reverse the initial 4326 coordinates [3.429960207,-76.495207812] and directly set to the marker, it shows perfect (without any proj4 tranformation).

1. Why that transform isn't working on Leaflet or what should I do to make it work?

2. Why reversing the coordinates it seems to work?

3. How should be the right way to solve the issue?


Solution

  • Leaflet uses latitude-longitude, whereas proj4 uses longitude-latitude (or, more generically, the axis order specified in the projection definition, which for most projections is easting-northing).

    Yes, some software uses lat-long and other software uses long-lat and it's confusing.

    If you're going to use only EPSG:4326 and EPSG:3857, consider using Leaflet's built-in L.CRS.EPSG3857.project and L.CRS.EPSG.3857.unproject, remember to check Leaflet's documentation. That way you'll work with one consistent axis order.