#!/usr/bin/env python3 """ دانلود tiles نقشه شیوه (Shiveh) برای شهر ساری منبع: سازمان نقشه‌برداری کشور (MapIR) """ import os import sys import time import math import ssl import urllib.request from pathlib import Path # SSL context for servers with weak DH keys SSL_CTX = ssl.create_default_context() SSL_CTX.set_ciphers('DEFAULT:@SECLEVEL=1') SSL_CTX.check_hostname = False SSL_CTX.verify_mode = ssl.CERT_NONE # ============================================= # آدرس سرور شیوه # ============================================= SHIVEH_URL_TEMPLATE = "https://gnaf4.post.ir/vector/xyz/1.0.0/Shiveh:Vector@EPSG:900913@pbf/{z}/{x}/{y}.pbf" # ============================================= # مختصات جغرافیایی شهر ساری (تقریبی) # ============================================= SARI_BOUNDS = { 'north': 36.585, # عرض جغرافیایی (شمال) 'south': 36.545, # عرض جغرافیایی (جنوب) 'east': 53.115, # طول جغرافیایی (شرق) 'west': 53.055 # طول جغرافیایی (غرب) } # سطوح زوم ZOOM_LEVELS = [12, 13, 14, 15, 16, 17, 18] def lat_lon_to_tile(lat, lon, zoom): """تبدیل مختصات جغرافیایی به شماره tile""" n = 2 ** zoom x = int((lon + 180) / 360 * n) lat_rad = math.radians(lat) y = int((1 - math.log(math.tan(lat_rad) + 1/math.cos(lat_rad)) / math.pi) / 2 * n) return x, y def tile_to_lat_lon(x, y, zoom): """تبدیل شماره tile به مختصات جغرافیایی""" n = 2 ** zoom lon = x / n * 360 - 180 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * y / n))) lat = math.degrees(lat_rad) return lat, lon def get_tile_range(bounds, zoom): """محاسبه محدوده tiles""" x_min, y_max = lat_lon_to_tile(bounds['north'], bounds['west'], zoom) x_max, y_min = lat_lon_to_tile(bounds['south'], bounds['east'], zoom) # اصلاح Y if y_min > y_max: y_min, y_max = y_max, y_min return x_min, x_max, y_min, y_max def download_tile(x, y, z, output_dir): """دانلود یک tile""" url = SHIVEH_URL_TEMPLATE.format(z=z, x=x, y=y) output_path = Path(output_dir) / str(z) / str(x) / f"{y}.pbf" # اگر قبلاً دانلود شده if output_path.exists() and output_path.stat().st_size > 100: return True, "exists" try: output_path.parent.mkdir(parents=True, exist_ok=True) req = urllib.request.Request(url, headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 'Accept': '*/*' }) with urllib.request.urlopen(req, timeout=15, context=SSL_CTX) as response: data = response.read() # بررسی اینکه واقعاً PBF هست if len(data) < 50: return False, "empty" with open(output_path, 'wb') as f: f.write(data) return True, "downloaded" except urllib.error.HTTPError as e: if e.code == 404: return False, "not_found" return False, f"HTTP {e.code}" except Exception as e: return False, str(e)[:50] def main(): print(""" ╔══════════════════════════════════════════════════════════════════╗ ║ دانلود نقشه شیوه (Shiveh) - شهر ساری ║ ║ منبع: سازمان نقشه‌برداری کشور ║ ╚══════════════════════════════════════════════════════════════════╝ """) # مسیر خروجی script_dir = Path(__file__).parent.parent output_dir = script_dir / "public" / "tiles" print(f" مسیر خروجی: {output_dir}") print(f" سرور: gnaf4.post.ir") print() print(f" محدوده جغرافیایی ساری:") print(f" شمال: {SARI_BOUNDS['north']}") print(f" جنوب: {SARI_BOUNDS['south']}") print(f" شرق: {SARI_BOUNDS['east']}") print(f" غرب: {SARI_BOUNDS['west']}") print() # محاسبه تعداد tiles total = 0 print(" محاسبه تعداد tiles...") for z in ZOOM_LEVELS: x_min, x_max, y_min, y_max = get_tile_range(SARI_BOUNDS, z) count = (x_max - x_min + 1) * (y_max - y_min + 1) total += count lat_n, lon_w = tile_to_lat_lon(x_min, y_min, z) lat_s, lon_e = tile_to_lat_lon(x_max, y_max, z) print(f" Zoom {z}: {count:>6} tiles ({x_max-x_min+1} × {y_max-y_min+1})") print(f"\n جمع کل: {total} tiles") print() # تایید response = input(" شروع دانلود؟ (y/n): ") if response.lower() != 'y': print(" لغو شد.") sys.exit(0) print() # دانلود downloaded = 0 skipped = 0 not_found = 0 errors = 0 for z in ZOOM_LEVELS: x_min, x_max, y_min, y_max = get_tile_range(SARI_BOUNDS, z) print(f"\n ▶ Zoom {z}...") for x in range(x_min, x_max + 1): for y in range(y_min, y_max + 1): success, status = download_tile(x, y, z, output_dir) if success: if status == "downloaded": downloaded += 1 else: skipped += 1 else: if status == "not_found": not_found += 1 else: errors += 1 # نمایش پیشرفت done = downloaded + skipped + not_found + errors total_this_zoom = (x_max - x_min + 1) * (y_max - y_min + 1) if done % 20 == 0: print(f" {done}/{total_this_zoom}", end='\r') time.sleep(0.05) # تأخیر برای جلوگیری از فشار print(f""" ╔══════════════════════════════════════════════════════════════════╗ ║ گزارش نهایی ║ ╠══════════════════════════════════════════════════════════════════╣ ║ ✓ دانلود شده: {downloaded:>6} ║ ║ - موجود (رد شده): {skipped:>6} ║ ║ ? موجود نبود: {not_found:>6} (طبیعی - بعضی نقاط خالی هستن) ║ ║ ✗ خطا: {errors:>6} ║ ╚══════════════════════════════════════════════════════════════════╝ """) if downloaded > 0: print(" ✓ دانلود با موفقیت انجام شد!") print(" حالا مرورگر را باز کنید و نقشه را ببینید.") elif not_found == total: print(" ! هیچ tileای پیدا نشد.") print(" ممکنه محدوده جغرافیایی اشتباه باشه.") if __name__ == "__main__": main()