improved osm renderning: full building outlines, roads, greenspace, water

This commit is contained in:
Evan Scamehorn
2025-11-26 16:09:03 -06:00
parent c4b29f5a20
commit 059a58fbf7
3 changed files with 288 additions and 162 deletions

View File

@@ -2,89 +2,146 @@ import osmnx as ox
import json
import os
# ==========================================
# 1. Configuration
# ==========================================
PLACE_NAME = "Wisconsin State Capitol, Madison, USA"
DIST = 2400 # Meters radius around center
DIST = 3000
# 2. Download Data
# ==========================================
# 2. Data Fetching
# ==========================================
print(f"Downloading data for {PLACE_NAME}...")
tags = {"building": True}
# UPDATED FOR V2.0: Access features module explicitly
# Define tags for different layers
tags = {
"building": True,
"natural": ["water", "bay", "coastline"],
"landuse": ["grass", "forest", "park", "recreation_ground"],
"leisure": ["park", "garden"],
"highway": True,
}
try:
# Try new v2.0 syntax
# OSMNX v2.0+
gdf = ox.features.features_from_address(PLACE_NAME, tags=tags, dist=DIST)
except AttributeError:
# Fallback for older versions
# OSMNX < v2.0
gdf = ox.features_from_address(PLACE_NAME, tags=tags, dist=DIST)
# 3. Project to meters (Local Grid)
# UPDATED FOR V2.0: Use GeoPandas native estimation
# ==========================================
# 3. Projection & Normalization
# ==========================================
print("Projecting to local grid...")
gdf_proj = gdf.to_crs(gdf.estimate_utm_crs())
# 4. Prepare Data for THREE.js
buildings = []
# Calculate center to normalize coordinates to (0,0)
# Calculate center for (0,0,0) normalization
center_x = gdf_proj.geometry.centroid.x.mean()
center_y = gdf_proj.geometry.centroid.y.mean()
print("Processing geometry...")
for _, row in gdf_proj.iterrows():
if row.geometry.geom_type == "Polygon":
# Get dimensions
minx, miny, maxx, maxy = row.geometry.bounds
width = maxx - minx
depth = maxy - miny
# ==========================================
# 4. Processing Functions
# ==========================================
# Get Height (Clean dirty data)
height = 10 # Default fallback
# Check for 'height' tag
if "height" in row and str(row["height"]) != "nan":
try:
# Clean strings like "10 m" or "approx 10"
clean_h = "".join(
filter(lambda x: x.isdigit() or x == ".", str(row["height"]))
def get_height(row):
"""Estimates building height from tags."""
h = 10.0 # Default
if "height" in row and str(row["height"]).lower() != "nan":
try:
# Extract numeric part
clean = "".join(
filter(lambda x: x.isdigit() or x == ".", str(row["height"]))
)
h = float(clean)
except:
pass
elif "building:levels" in row and str(row["building:levels"]).lower() != "nan":
try:
clean = "".join(
filter(lambda x: x.isdigit() or x == ".", str(row["building:levels"]))
)
h = float(clean) * 3.5
except:
pass
return round(h, 1)
def parse_polygon(geom):
"""Extracts exterior coordinates from a Polygon."""
if geom.is_empty:
return []
coords = list(geom.exterior.coords)
# Simplify slightly to reduce vertex count if needed, or keep raw
return [[round(x - center_x, 1), round(y - center_y, 1)] for x, y in coords]
def parse_linestring(geom):
"""Extracts coordinates from a LineString."""
if geom.is_empty:
return []
coords = list(geom.coords)
return [[round(x - center_x, 1), round(y - center_y, 1)] for x, y in coords]
# ==========================================
# 5. Categorization Loop
# ==========================================
output_data = {"buildings": [], "water": [], "parks": [], "roads": []}
print("Processing geometries...")
for idx, row in gdf_proj.iterrows():
geom = row.geometry
# Handle MultiPolygons by iterating over them
geoms = [geom] if geom.geom_type in ["Polygon", "LineString"] else []
if geom.geom_type == "MultiPolygon":
geoms = list(geom.geoms)
elif geom.geom_type == "MultiLineString":
geoms = list(geom.geoms)
for sub_geom in geoms:
# 1. BUILDINGS
if "building" in row and str(row["building"]) != "nan":
if sub_geom.geom_type == "Polygon":
output_data["buildings"].append(
{"shape": parse_polygon(sub_geom), "height": get_height(row)}
)
height = float(clean_h)
except:
pass
# Check for 'building:levels' tag
elif "building:levels" in row and str(row["building:levels"]) != "nan":
try:
clean_l = "".join(
filter(
lambda x: x.isdigit() or x == ".", str(row["building:levels"])
)
)
height = float(clean_l) * 3.5 # Approx 3.5m per floor
except:
pass
# Normalize position relative to center
x = (minx + maxx) / 2 - center_x
z = center_y - (miny + maxy) / 2 # Invert Y for 3D Z-axis
# 2. WATER
elif ("natural" in row and row["natural"] in tags["natural"]) or (
"water" in row and str(row["water"]) != "nan"
):
if sub_geom.geom_type == "Polygon":
output_data["water"].append({"shape": parse_polygon(sub_geom)})
# Add to array: [x, z, width, depth, height]
buildings.append(
[
round(x, 1),
round(z, 1),
round(width, 1),
round(depth, 1),
round(height, 1),
]
)
# 3. PARKS / GREENSPACE
elif ("leisure" in row and row["leisure"] in tags["leisure"]) or (
"landuse" in row and row["landuse"] in tags["landuse"]
):
if sub_geom.geom_type == "Polygon":
output_data["parks"].append({"shape": parse_polygon(sub_geom)})
# 5. Save to Public folder
# 4. ROADS
elif "highway" in row and str(row["highway"]) != "nan":
if sub_geom.geom_type == "LineString":
output_data["roads"].append({"path": parse_linestring(sub_geom)})
# ==========================================
# 6. Save File
# ==========================================
output_path = os.path.join(os.path.dirname(__file__), "../public/city_data.json")
# Ensure directory exists just in case
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, "w") as f:
json.dump(buildings, f)
json.dump(output_data, f)
print(f"Done! Saved {len(buildings)} buildings to {output_path}")
print(
f"Exported:"
f"\n Buildings: {len(output_data['buildings'])}"
f"\n Roads: {len(output_data['roads'])}"
f"\n Water: {len(output_data['water'])}"
f"\n Parks: {len(output_data['parks'])}"
)
print(f"Saved to {output_path}")