Spaces:
Sleeping
Sleeping
File size: 2,208 Bytes
0c02b78 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | import requests
import json
from shapely.geometry import shape, mapping, Polygon, MultiPolygon
from shapely.ops import unary_union
import urllib.parse
def fetch_boundary(state):
url = f"https://nominatim.openstreetmap.org/search?state={urllib.parse.quote(state)}&country=India&polygon_geojson=1&format=json"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"}
res = requests.get(url, headers=headers)
res.raise_for_status()
data = res.json()
for item in data:
if item.get('geojson') and item['geojson']['type'] in ['Polygon', 'MultiPolygon']:
return shape(item['geojson'])
return None
states = ["Maharashtra", "Goa", "Karnataka"]
polys = []
for s in states:
print(f"Fetching {s} boundary...")
poly = fetch_boundary(s)
if poly:
polys.append(poly)
else:
print(f"Could not find boundary for {s}")
if polys:
print("Merging boundaries...")
merged = unary_union(polys)
# Create an outer bounding box that covers the world (or a large enough area)
outer = Polygon([(-180, -90), (180, -90), (180, 90), (-180, 90)])
# Create the inverse mask (hole)
mask = outer.difference(merged)
geojson_mask = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": mapping(mask),
"properties": {}
}
]
}
geojson_bounds = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": mapping(merged),
"properties": {}
}
]
}
out_mask_path = "frontend/public/data/multi_state_mask.json"
out_bounds_path = "frontend/public/data/state_boundaries.json"
with open(out_mask_path, 'w') as f:
json.dump(geojson_mask, f)
with open(out_bounds_path, 'w') as f:
json.dump(geojson_bounds, f)
print(f"Mask saved to {out_mask_path}")
print(f"Boundaries saved to {out_bounds_path}")
else:
print("Failed to fetch polygons.")
|