Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate bounding box of static google maps image

Tags:

Lets say I request this image from the google static maps API

https://maps.googleapis.com/maps/api/staticmap?center=52.591370,-2.110748&zoom=18&size=600x600&maptype=satellite&markers=color:blue|52.591370,-2.110748

I get a 600px x 600px image centered at 52.591370,-2.110748. Given the center, the image size and the zoom level, how can I calculate the bounding box of the image in lat lng coordinates. More specifically, how can I calculate the lat/lng of the the bottom left corner and the top right corner.

I have done some research and looked at mercator projection but the articles keep mentioning tile size which is not relevant in this case.

Can anyone help ?

like image 605
Connor Bishop Avatar asked Jun 27 '17 15:06

Connor Bishop


1 Answers

const _C = { x: 128, y: 128 };
const _J = 256 / 360;
const _L = 256 / (2 * Math.PI);

function tb(a) {
    return 180 * a / Math.PI
}

function sb(a) {
    return a * Math.PI / 180
}

function bounds(a, b, c) {
    null != b && (a = Math.max(a, b));
    null != c && (a = Math.min(a, c));
    return a
}

function latlonToPt(ll) {
  a = bounds(Math.sin(sb(ll[0])), -(1 - 1E-15), 1 - 1E-15);
  return {
    x: _C.x + ll[1] * _J,
    y: _C.y + 0.5 * Math.log((1 + a) / (1 - a)) * - _L
  }
}

function ptToLatlon(pt) {
    return [tb(2 * Math.atan(Math.exp((pt.y - _C.y) / -_L)) - Math.PI / 2),(pt.x - _C.x) / _J]
}


function calculateBbox(ll, zoom, sizeX, sizeY) {
    const cp = latlonToPt(ll);
    const pixelSize = Math.pow(2, -(zoom+1));
    const pwX = sizeX*pixelSize;
    const pwY = sizeY*pixelSize;

    return {
      ne: ptToLatlon({x: cp.x + pwX, y: cp.y - pwY}),
      sw: ptToLatlon({x: cp.x - pwX, y: cp.y + pwY})
    }
}

This solution doesn't require including the Google Map client side map. See example: https://jsfiddle.net/1wy1mm7L/6/

like image 150
amersk Avatar answered Sep 23 '22 11:09

amersk