Search code examples
leafletp2p

Get XY Tile Coordinate at Z Zoom Level with Leaflet


I have figured out how to get XYZ coordinates by extending Leaflet with a createTile function.

But what I'm wanting to know is how do I access the XY tile name/coordinate for a fixed Z zoom level around my GPS coordinates, even if I'm not zoomed in.

Why? I'm working on a P2P/decentralized version of Uber, and the XY coordinates are a good common/shared location index for users to lookup/subscribe/query against. As in, everybody within that X mile radius all will know the same XY coordinate name and use that as a deterministic key to find each other with.


Solution

  • This project will "Convert lon, lat to screen pixel x, y from 0, 0 origin, at a certain zoom level." https://github.com/mapbox/sphericalmercator

    UPDATED:

    function lng2tile(lon,z) { return (Math.floor((lon+180)/360*Math.pow(2,z))) }
    function lat2tile(lat,z)  { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,z))) }
    

    Or try this:

    var row = Math.floor((location.lng + 180) / (360 / Math.pow(2, zoomLevel)));
    var col = Math.floor((90 + (location.lat * -1)) / (180 / Math.pow(2, (zoomLevel - 1))));