wmts-exfiltrator/pkg/spatial.py

36 lines
1.2 KiB
Python

from rasterio import Affine
import math
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** 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
def calculate_transform(args, min_col, max_col, min_row, max_row):
# Constants for Web Mercator (EPSG:3857)
tile_size_in_pixels = 256
earth_circumference = 40075016.686 # in meters
# Calculate the size of a tile in meters at the given zoom level
tile_size_in_meters = earth_circumference / (2 ** args.zoom)
# Calculate the geographic coordinates of the bounding box
min_x = min_col * tile_size_in_meters
max_x = (max_col + 1) * tile_size_in_meters
min_y = (2 ** args.zoom - max_row - 1) * tile_size_in_meters
max_y = (2 ** args.zoom - min_row) * tile_size_in_meters
# Calculate the pixel size in x and y directions
pixel_size_x = tile_size_in_meters / tile_size_in_pixels
pixel_size_y = tile_size_in_meters / tile_size_in_pixels
# Define the transformation
transform = Affine.translation(min_x, min_y) * Affine.scale(pixel_size_x, -pixel_size_y)
return transform