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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With