snippets/geo_tiles_assembler/download_tiles_within_bounds.py

58 lines
1.6 KiB
Python

import requests
import os
import math
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 1 << zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n)
return xtile, ytile
# around chatillon
BOUNDS = ((48.8, 2.26), (48.82, 2.32))
BOUNDS = ((48.5, 2.1), (49.9, 2.6))
BASE_URL = os.getenv("SOURCE_BASE_URL")
BASE_DIR = os.getenv("OUTPUT_BASE_DIR")
LAYERS = os.getenv("LAYERS_NAMES")
iz = 0
for z in range(10, 15):
TILES_BOUNDS = (
deg2num(BOUNDS[0][0], BOUNDS[0][1], z),
deg2num(BOUNDS[1][0], BOUNDS[1][1], z)
)
maxx = 0
maxy = 0
xrange = range(TILES_BOUNDS[0][0], TILES_BOUNDS[1][0])
yrange = range(TILES_BOUNDS[1][1], TILES_BOUNDS[0][1])
print(TILES_BOUNDS)
print(xrange, yrange)
iy = 0
for y in reversed(yrange):
ix = 0
for x in xrange:
url = f"{BASE_URL}/{LAYERS}/{z}/{x}/{y}"
dir_path = f'{BASE_DIR}/tiles/{LAYERS}/{z}/{x}'
tile_path = dir_path + f'/{y}'
img_data = 0
print(tile_path)
if not os.path.exists(tile_path):
print(url)
res = requests.get(url)
if res.status_code >= 300:
print(res.content)
exit()
img_data = res.content
os.makedirs(dir_path, exist_ok=True)
with open(tile_path, 'wb') as handler:
handler.write(img_data)
ix += 1
iy += 1
iz += 1
print("DONE")