#!/usr/bin/env python3 import sqlite3 import json import subprocess import sys from pathlib import Path def read_bounds(tif): info = json.loads(subprocess.check_output(["gdalinfo", "-json", tif])) if "wgs84Extent" in info: coords = info["wgs84Extent"]["coordinates"][0] minlon, minlat = coords[0] maxlon, maxlat = coords[2] else: cc = info["cornerCoordinates"] minlon, minlat = cc["lowerLeft"] maxlon, maxlat = cc["upperRight"] if minlat > maxlat: minlat, maxlat = maxlat, minlat if minlon > maxlon: minlon, maxlon = maxlon, minlon return ( round(minlon, 6), round(minlat, 6), round(maxlon, 6), round(maxlat, 6), ) def main(): if len(sys.argv) != 4: print("Uso: python3 set_mbtiles_metadata_multi.py raster1.tif raster2.tif merged.mbtiles") sys.exit(1) tif1 = Path(sys.argv[1]) tif2 = Path(sys.argv[2]) mbtiles = Path(sys.argv[3]) b1 = read_bounds(tif1) b2 = read_bounds(tif2) W = min(b1[0], b2[0]) S = min(b1[1], b2[1]) E = max(b1[2], b2[2]) N = max(b1[3], b2[3]) bounds = f"{W:.6f},{S:.6f},{E:.6f},{N:.6f}" conn = sqlite3.connect(mbtiles) cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS metadata (name TEXT PRIMARY KEY, value TEXT);") cur.execute("SELECT MIN(zoom_level), MAX(zoom_level) FROM tiles;") minzoom, maxzoom = cur.fetchone() centerLon = (W + E) / 2 centerLat = (S + N) / 2 centerZoom = (minzoom + maxzoom) // 2 center = f"{centerLon:.6f},{centerLat:.6f},{centerZoom}" cur.execute("REPLACE INTO metadata VALUES ('bounds', ?)", (bounds,)) cur.execute("REPLACE INTO metadata VALUES ('center', ?)", (center,)) cur.execute("REPLACE INTO metadata VALUES ('minzoom', ?)", (str(minzoom),)) cur.execute("REPLACE INTO metadata VALUES ('maxzoom', ?)", (str(maxzoom),)) cur.execute("REPLACE INTO metadata VALUES ('format', 'png')") cur.execute("REPLACE INTO metadata VALUES ('type', 'overlay')") cur.execute("REPLACE INTO metadata VALUES ('scheme', 'xyz')") conn.commit() conn.close() print("Metadata scritti correttamente:") print("bounds:", bounds) print("center:", center) print("minzoom:", minzoom) print("maxzoom:", maxzoom) print("format: png") print("type: overlay") print("scheme: xyz") if __name__ == "__main__": main()