1

I am struggling a bit moving from Leaflet to Mapbox. I have geojson with coordinates like [68100095, 100779149], which I am told are Mercator x/y coordinates at a zoom level of 20. This is how the data is stored.

In Leaflet, I could translate these coordinates to latitude and longitude using map.unproject([68100095, 100779149], 20, specifying the coordinates and then the zoom level. It works as intended.

In Mapbox, unproject does not allow you to specify a zoom level, and unprojects based on your current zoom level, which I cannot guarantee. My attempted solution is to use Proj4js and an NPM package called mercator-projection, which is meant to project mercator coordinates to latitude/longitude. My solution, which yields erratic results, is as follows:

function mercator_to_lnglat(x, y) {
    const SCALE_ADJUSTMENT = 564.248588    //Adjust for zoom level of 20

    let scaledPoint = [x/SCALE_ADJUSTMENT, y/SCALE_ADJUSTMENT]
    let projectedPoint = proj4("GOOGLE", "WGS84", scaledPoint)
    let latlng = merc.fromPointToLatLng({x: projectedPoint[0], y: projectedPoint[1]})

    return latlng
}

SCALE_ADJUSTMENT here is a magic number I got from this ArcGIS link that calculated an equivalent scaling factor for a zoom level of 20.

I'm no GIS expert, so I would be thrilled if anyone could point out what I'm doing incorrectly here.

2
  • This is helpful, and explains some of what I was seeing in the Leaflet source! I'll follow that lead when I get back to it. Aug 12 at 8:06
  • Got it! Thanks for your help. It was much simpler than I was making it, but I never would have got it without your explainer. If you would like to formulate your guidance as an answer, I would gladly accept and add my specific solution as a comment. (There is a package called coordinates2pixels that did the thinking, once you set me on the right path.) If I don't hear back after a day or so, I'll go ahead and answer myself. Aug 12 at 8:58

1 Answer 1

1

If you are using map.project and map.unproject methods in Leaflet for projecting/unprojecting coordinates, these are not Mercator coordinates, but "pixel coordinates relative to the CRS origin", see https://leafletjs.com/reference.html#map-conversion-methods.

If you want to project/unproject Mercator coordinates in Leaflet, you have to use .project and .unproject methods of L.CRS.EPSG3857 projection, see https://leafletjs.com/reference.html#crs.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.