1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import math
TILE_SIZE = 256
def lon_to_pixel_x(lon, zoom): pixel_x = (lon + 180) / 360 * (TILE_SIZE << zoom) return pixel_x
def lat_to_pixel_y(lat, zoom): sin_lat = math.sin(lat * math.pi / 180) return (0.5 - math.log((1 + sin_lat) / (1 - sin_lat)) / (4 * math.pi)) * (TILE_SIZE << zoom)
def lat_lon_to_tile(lon, lat, zoom): px = lon_to_pixel_x(lon, zoom) py = lat_to_pixel_y(lat, zoom) tx = int(px / TILE_SIZE) ty = int(py / TILE_SIZE) return tx, ty
def tile_to_latlon(x, y, z): n = 2.0 ** z lon_left = x / n * 360.0 - 180.0 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * y / n))) lat_top = math.degrees(lat_rad)
lon_right = (x + 1) / n * 360.0 - 180.0 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * (y + 1) / n))) lat_bottom = math.degrees(lat_rad)
return lat_top, lon_left, lat_bottom, lon_right
if __name__ == "__main__": print(tile_to_latlon(14, 6, 4)) print(lat_lon_to_tile(135, 40.97, 4))
|