Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Leaflet LatLng to tile pixel coordinates

For canvas layers, how can I access the clicked pixel of a specific tile? Given a LatLng like { lat: 37.68816, lng: -119.76196 }, how can I: #1, retrieve the correct tile clicked, and #2, the pixel coordinates within the tile? Both of these should consider maxNativeZoom.

like image 518
nathancahill Avatar asked Dec 06 '16 01:12

nathancahill


1 Answers

A CRS like L.CRS.EPSG3857 is required. The map's CRS is accessible by map.options.crs. The true zoom, tile size (like 256, but could be 512 or higher about maxNativeZoom) and a pixel origin like map.getPixelOrigin() are required:

const latlngToTilePixel = (latlng, crs, zoom, tileSize, pixelOrigin) => {
    const layerPoint = crs.latLngToPoint(latlng, zoom).floor()
    const tile = layerPoint.divideBy(tileSize).floor()
    const tileCorner = tile.multiplyBy(tileSize).subtract(pixelOrigin)
    const tilePixel = layerPoint.subtract(pixelOrigin).subtract(tileCorner)

    return [tile, tilePixel]
}

First, convert the latlng to a layer point. Now all units are in pixels.

Second, divide by tileSize and round down. This gives the tile "slippy" coordinates.

Third, multiply back by tileSize to get the pixel coordinates of the tile corner, adjusted for pixelOrigin.

Finally, to get the tile pixels, subtract the layer point from origin and tile corner.

like image 132
nathancahill Avatar answered Sep 21 '22 13:09

nathancahill