Friday, 20 February 2015

Corner coordinates of Google static map tile


How to calculate the corner coordinates (bounding box) of a static Google Map image, fetched with e.g. http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=400x400&sensor=false ?



Answer



I think this is not so hard a problem to solve but I have my doubts about whether the accuracy is absolutely correct. First of all, you have to convert your center lat/lon to pixels with gdal2tiles codes. If I find some time and if you want, I can convert it to stable code for finding corner coordinates.



This is a Python code:


tileSize = 256
initialResolution = 2 * math.pi * 6378137 / tileSize
# 156543.03392804062 for tileSize 256 pixels
originShift = 2 * math.pi * 6378137 / 2.0
# 20037508.342789244

def LatLonToMeters( lat, lon ):
"Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913"


mx = lon * originShift / 180.0
my = math.log( math.tan((90 + lat) * math.pi / 360.0 )) / (math.pi / 180.0)

my = my * originShift / 180.0
return mx, my


def MetersToPixels( mx, my, zoom):
"Converts EPSG:900913 to pyramid pixel coordinates in given zoom level"


res = Resolution( zoom )
px = (mx + originShift) / res
py = (my + originShift) / res
return px, py


# Dont forget you have to convert your projection to EPSG:900913
mx = -8237494.4864285 #-73.998672
my = 4970354.7325767 # 40.714728
zoom = 12


pixel_x, pixel_y = LatLonToMeters(MetersToPixels( mx, my, zoom))

Then you can use addition or substraction by looking the following image:


MATH


If you want to find point A :


x = pixel_x - 200
y = pixel_y + 200

or you want to find point B:



x = pixel_x + 200
y = pixel_y + 200

and the last thing is that you have to do is convert your pixels to lat/lon.


def PixelsToMeters( px, py, zoom):
"Converts pixel coordinates in given zoom level of pyramid to EPSG:900913"

res = Resolution(zoom)
mx = px * res - originShift
my = py * res - originShift

return mx, my

def MetersToLatLon( mx, my ):
"Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"

lon = (mx / originShift) * 180.0
lat = (my / originShift) * 180.0

lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi / 180.0)) - math.pi / 2.0)
return lat, lon





#Result

llx, lly = MetersToLatLon( PixelsToMeters( x, y, zoom) )

so the result I have:


point A - UpperLeftLatLon = 40.7667530977 -74.0673365509

point B - UpperRightLatLon = 40.7667530977 -73.9300074493
point C - LowerRightLatLon = 40.6626622172 -73.9300074493
point D - LowerLeftLatLon = 40.6626622172 -74.0673365509

I hope it helps you....


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...