Théo Champion
Théo Champion

Reputation: 1988

Map Web Mercator pixel coordinates to screen pixel

I'm trying to make an overlay over a google map (for Flutter which lacks the dedicated library atm).

I have a function to get the projection in pixel coordinates for the lat, lng and zoom:

const project = (latitude, longitude, zoomlevel) => {
    // Adapted from: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates
    
    const TILE_SIZE = 256;                               // Pixel size of the base tile.
    const ORIGIN = TILE_SIZE / 2;                        // The point to which LatLng (0, 0) projects.
    const PIXELS_PER_DEGREE = TILE_SIZE / 360;           // Number of pixels of world coords for every degree.
    const PIXELS_PER_RADIAN = TILE_SIZE / (2 * Math.PI); // Number of pixels of world coords for every radian.
    
    // X position is easy. It's a simple mapping from longitude to pixels. However
    // because world coordinates are from 0,0 at the top left, and the lat/long will
    // map to the center, we need to offset by half a tile so there are no negative
    // coordinates.
    const worldX = ORIGIN + longitude * PIXELS_PER_DEGREE;
    
    // Formula here: https://en.wikipedia.org/wiki/Web_Mercator#Formulas
    // Some explanation of the math: http://mathworld.wolfram.com/MercatorProjection.html
    // Convert latitude to radians, and take the sine. Then clamp the value to avoid log(0) or log(1), which
    // are infinity and 0 (poles are flawed in Mercator).
    let sinY = Math.sin(latitude * Math.PI / 180);
    sinY = Math.min(Math.max(sinY, -0.9999), 0.9999);
    const worldY = ORIGIN + 0.5 * (Math.log((1 + sinY) / (1 - sinY)) * -PIXELS_PER_RADIAN);
    
    
    const scale = Math.pow(2, zoomlevel);
    const pixelX = worldX * scale;
    const pixelY = worldY * scale;
    return {x: pixelX, y: pixelY}
}

and I know the dimension in pixel of my device screen.

What I can't seem to figure out is how to map the pixel coordinates of a point their screen coordinates.

Does anyone have an idea?

Cheers! :)

Upvotes: 2

Views: 1092

Answers (0)

Related Questions