I'm using the MapBox or Google Maps Static API to get map images. I understand that the centre of the image is specified in terms of latitude and longitude, but is there any way to either specify or derive the extent or bounding box of the image given its centre coordinates and size?


Since MapBox uses the Web Mercator projection (also used by Google Maps etc), the key lies in these two equations:

Formulas from Web Mercator on Wikipedia: https://en.wikipedia.org/wiki/Web_Mercator#Formulas

where λ is the longitude in radians and φ is geodetic latitude in radians. The x and y values are the so-called 'pixel coordinates' as originally defined by Google.

What you actually need are the inverse of these two equations, so that you can convert the latitude and longitude into x and y values. The inverse equations are:

Inverse Lambda equation

enter image description here


enter image description here

Given the centre co-ordinates of your image as defined by λ and φ, convert these into the x and y pixel coordinates for your chosen zoom level using the inverse equations above. If h is the height of your image, and w is its width, you can then calculate the (l)eft, (r)ight, (t)op and (b)ottom pixel coordinates of your image:

l = x - (w/2)
r = x + (w/2)
t = y - (h/2) (since zero is at the top for Web Mercator pixels)
b = y + (h/2)

Then, convert back into latitude and longitude using the original equations, substituting l or r for x, and t or b for y.

EDIT: Trying this with the non-Retina MapBox Static API, I found that I had to use a factor of 4 instead of 2 in the last four equations. Not sure why this is, but probably something to do with internal scaling in the MapBox servers.


https://github.com/mapbox/geo-viewport allows you to convert both ways:

geoViewport.viewport Given a WSEN array of bounds and a [x, y] array of pixel dimensions, return a { center: [lon, lat], zoom: zoom } viewport.

geoViewport.bounds Given a centerpoint as [lon, lat] or { lon, lat }, a zoom, and dimensions as [x, y], return a bounding box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.