Created
May 21, 2022 12:50
-
-
Save breqdev/8f14e0ea0daf46716ca8865ca4c6065a to your computer and use it in GitHub Desktop.
Download map tiles for an area
This file contains 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
import math | |
import pathlib | |
import requests | |
root = pathlib.Path("tiles") | |
base_url = "https://tile.openstreetmap.org/{zoom}/{x}/{y}.png" | |
tile_format = "png" | |
def download_tile(zoom: int, x: int, y: int): | |
url = base_url.format(zoom=zoom, x=x, y=y) | |
r = requests.get(url) | |
r.raise_for_status() | |
tile_path = root / f"{zoom}" / f"{x}" | |
tile_path.mkdir(parents=True, exist_ok=True) | |
with open(tile_path / f"{y}.{tile_format}", "wb") as f: | |
f.write(r.content) | |
def latlon_to_tile(lat, lon, zoom): | |
lat_rad = math.radians(lat) | |
n = 2.0**zoom | |
x = int((lon + 180.0) / 360.0 * n) | |
y = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n) | |
return (x, y) | |
def download_area(lat_min, lat_max, lon_min, lon_max): | |
for zoom in range(16): | |
min_x, min_y = latlon_to_tile(lat_min, lon_min, zoom) | |
max_x, max_y = latlon_to_tile(lat_max, lon_max, zoom) | |
for x in range(min_x, max_x + 1): | |
for y in range(min_y, max_y + 1): | |
download_tile(zoom, x, y) | |
download_area(38.452728, 38.343344, -110.851391, -110.671355) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment