Created
March 15, 2023 06:30
-
-
Save hfs/8057cf5d2b1b34d122641b7531d359a8 to your computer and use it in GitHub Desktop.
Convert a bounding box given as two longitude/latitude pairs into a list of map tile coordinates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import math | |
import re | |
import sys | |
def deg2num(lng_deg, lat_deg, zoom): | |
lat_rad = math.radians(lat_deg) | |
n = 2.0 ** zoom | |
xtile = int((lng_deg + 180.0) / 360.0 * n) | |
ytile = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n) | |
return (xtile, ytile) | |
def enumerate_tiles(zoom, lng_min, lat_min, lng_max, lat_max): | |
tile_min = deg2num(lng_min, lat_min, zoom) | |
tile_max = deg2num(lng_max, lat_max, zoom) | |
for y in range(tile_max[1], tile_min[1] + 1): | |
for x in range(tile_min[0], tile_max[0] + 1): | |
yield (x, y) | |
def main(): | |
parser = argparse.ArgumentParser( | |
prog='bbox2tiles', | |
description='List tile coordinates for a given bounding box in longitude-latitude and zoom') | |
parser.add_argument('zoom', type=int) | |
parser.add_argument('bbox', help="lng_min,lat_min,lng_max,lat_max") | |
args = parser.parse_args() | |
bbox = tuple(map(float, re.split(r'\s*,\s*', args.bbox))) | |
for tile_coordinate in enumerate_tiles(args.zoom, *bbox): | |
print(f"{args.zoom}/{tile_coordinate[0]}/{tile_coordinate[1]}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment