[GIS] calculating bounding box from known centre coordinate and zoom

geodesicgpslatitude longitudeweb-mercator

I have a map, the centre of that map (centrepoint) is = -37,175 ( gps)
I know the zoom of the map = 13
I know the size = 320x320px
I know there is 111111m in a degree of latitude and a varying degree in longitude

I want to be able to calculate the value to add and subtract from the centre coordinate that will give me an upperleft/lowerright gps coordinate.

For a zoom of 13 I used to achieve this by
Note :centrelat= -37
eg :-37 – (-37/1650) = -36.9776 deg. In other words to find the southeast corner we subtracted .0228 degrees from the centre coordinate.
I did the same for longitude but used the value 6250
eg :175 – (175/6250) (.02804 degrees). = 174.792, ie the northwest corner
the ratio between .0228 degrees (lat)and .0280 degrees(long) is correct

So, I want this calculation to be dynamic and work for all zooms
so I'm using (cos Latitude x 111111) / 2^Zoom(13) = 10.72095
for longitude I'm using 111111/2^13 = 13.56
This is the same ratio as well so I'm on the right track!
but how do I use these values in a calculation to add or subtract degrees from the centre coordinates for lat and long to get the coordinates for the corners of the bounding box.

any help is appreciated, and I do mean that.

Best Answer

Assuming you are using the Web Mercator projection (Google Maps, MapBox 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

Inverse phi equation

where

F equation

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 first two 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) (minus 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.