with open('exported.geojson') as f:
data = geojson.load(f)
Process each feature to add lat and lon properties
for feature in data['features']:
if 'center' in feature:
feature['properties']['lat'] = feature['center']['lat']
feature['properties']['lon'] = feature['center']['lon']
del feature['center']
elif feature['geometry']['type'] == 'Point':
lon, lat = feature['geometry']['coordinates']
feature['properties']['lat'] = lat
feature['properties']['lon'] = lon
Save the processed GeoJSON
with open('buildings_with_latlon.geojson', 'w') as f:
geojson.dump(data, f)
So, I have that code to add lat/lon properies to the geojson file containing building footprint data. Before applying that code, can you automate the geojson download of building footprint data from openstreetmap using overpass turbo, for the extent of urbanized areas from input/landscan_hd.tif raster (EPSG:4326)
Assistant
Certainly! Automating the download of building footprint data from OpenStreetMap (OSM) using Overpass API based on the extent of urbanized areas defined by your landscan_hd.tif raster involves several steps. Below is a comprehensive guide, including a Python script that performs the entire workflow:
Load and Process the Raster to Define Urban Areas
Extract the Urbanized Area's Bounding Box or Polygon
Query Overpass API for Building Footprints within the Defined Area
Process the Retrieved GeoJSON to Add Latitude and Longitude Properties
Prerequisites
Before proceeding, ensure you have the following Python libraries installed:
1. Load and Process the Raster to Define Urban Areas
Assuming landscan_hd.tif is a population density raster in EPSG:4326, we will define "urbanized areas" based on a population density threshold. Adjust the threshold according to your specific criteria.
python
import rasterio
from rasterio.features import shapes
import numpy as np
import geopandas as gpd
from shapely.geometry import shape, mapping
import json
import requests
import geojson
# Define the path to your LandScan raster
raster_path = 'landscan_hd.tif'
# Define population density threshold for urbanization (adjust as needed)
POPULATION_THRESHOLD = 1000 # e.g., people per square kilometer
# Load the raster data
with rasterio.open(raster_path) as src:
data = src.read(1) # Read the first band
transform = src.transform
crs = src.crs
# Create a mask for urbanized areas
urban_mask = data > POPULATION_THRESHOLD
# Extract shapes (polygons) from the mask
results = (
{'geometry': shape(geom), 'value': value}
for geom, value in shapes(urban_mask.astype(np.int16), mask=urban_mask, transform=transform)
)
# Convert shapes to GeoDataFrame
geoms = list(results)
urban_geometries = [feature['geometry'] for feature in geoms if feature['value'] == 1]
# Combine all urban polygons into a single geometry (dissolve)
urban_union = urban_geometries[0]
for geom in urban_geometries[1:]:
urban_union = urban_union.union(geom)
# Optional: Simplify the geometry to reduce complexity
urban_union = urban_union.simplify(tolerance=0.01, preserve_topology=True)
# Save the urban area polygon (optional)
urban_gdf = gpd.GeoDataFrame({'geometry': [urban_union]}, crs=crs)
urban_gdf.to_file('urban_area.geojson', driver='GeoJSON')
2. Extract the Urbanized Area's Bounding Box
For simplicity and to reduce the complexity of the Overpass query, we'll use the bounding box of the urbanized area. However, for more precise results, you can use the polygon itself.
python
# Get the bounding box of the urban area
minx, miny, maxx, maxy = urban_union.bounds
# Overpass API expects bounding box in [south, west, north, east] order
bbox = [miny, minx, maxy, maxx]
3. Query Overpass API for Building Footprints within the Defined Area
We'll construct an Overpass QL query to retrieve building footprints (way["building"]) within the specified bounding box.
python
# Construct Overpass QL query
overpass_query = f"""
[out:geojson][timeout:600];
(
way["building"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
relation["building"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
);
out body;
>;
out skel qt;
"""
# Overpass API endpoint
overpass_url = "http://overpass-api.de/api/interpreter"
# Send the request
print("Sending request to Overpass API...")
response = requests.post(overpass_url, data={'data': overpass_query})
# Check for successful response
if response.status_code == 200:
with open('buildings.geojson', 'w', encoding='utf-8') as f:
f.write(response.text)
print("Building footprints downloaded and saved to buildings.geojson")
else:
print(f"Error fetching data from Overpass API: {response.status_code}")
print(response.text)
Notes:
Timeouts and Limits: The [timeout:600] sets the query timeout to 10 minutes. Adjust as necessary. Overpass API has rate limits; for large areas, you might need to split the query into smaller bounding boxes.
Complex Queries: For very large urban areas, consider querying in smaller sections to avoid timeouts or incomplete data.
4. Process the Retrieved GeoJSON to Add Latitude and Longitude Properties
Now, integrate your existing code to add lat and lon properties to each feature.
python
import geojson
import json
# Load the downloaded GeoJSON data
with open('buildings.geojson') as f:
data = geojson.load(f)
# Function to calculate the centroid of a geometry
def calculate_centroid(geometry):
geom_shape = shape(geometry)
centroid = geom_shape.centroid
return centroid.y, centroid.x # lat, lon
# Process each feature to add lat and lon properties
for feature in data['features']:
if 'center' in feature:
feature['properties']['lat'] = feature['center']['lat']
feature['properties']['lon'] = feature['center']['lon']
del feature['center']
elif feature['geometry']['type'] == 'Point':
lon, lat = feature['geometry']['coordinates']
feature['properties']['lat'] = lat
feature['properties']['lon'] = lon
else:
# For polygons and lines, calculate the centroid
lat, lon = calculate_centroid(feature['geometry'])
feature['properties']['lat'] = lat
feature['properties']['lon'] = lon
# Save the processed GeoJSON
with open('buildings_with_latlon.geojson', 'w') as f:
geojson.dump(data, f)
print("Processed GeoJSON saved to buildings_with_latlon.geojson")
Full Integrated Script
For convenience, here's the complete script combining all the steps:
python
import rasterio
from rasterio.features import shapes
import numpy as np
import geopandas as gpd
from shapely.geometry import shape, mapping
import json
import requests
import geojson
# Step 1: Load and Process the Raster to Define Urban Areas
raster_path = 'landscan_hd.tif'
POPULATION_THRESHOLD = 1000 # Adjust as needed
with rasterio.open(raster_path) as src:
data = src.read(1)
transform = src.transform
crs = src.crs
urban_mask = data > POPULATION_THRESHOLD
results = (
{'geometry': shape(geom), 'value': value}
for geom, value in shapes(urban_mask.astype(np.int16), mask=urban_mask, transform=transform)
)
geoms = list(results)
urban_geometries = [feature['geometry'] for feature in geoms if feature['value'] == 1]
urban_union = urban_geometries[0]
for geom in urban_geometries[1:]:
urban_union = urban_union.union(geom)
urban_union = urban_union.simplify(tolerance=0.01, preserve_topology=True)
urban_gdf = gpd.GeoDataFrame({'geometry': [urban_union]}, crs=crs)
urban_gdf.to_file('urban_area.geojson', driver='GeoJSON')
# Step 2: Extract the Urbanized Area's Bounding Box
minx, miny, maxx, maxy = urban_union.bounds
bbox = [miny, minx, maxy, maxx]
# Step 3: Query Overpass API for Building Footprints
overpass_query = f"""
[out:geojson][timeout:600];
(
way["building"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
relation["building"]({bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]});
);
out body;
>;
out skel qt;
"""
overpass_url = "http://overpass-api.de/api/interpreter"
print("Sending request to Overpass API...")
response = requests.post(overpass_url, data={'data': overpass_query})
if response.status_code == 200:
with open('buildings.geojson', 'w', encoding='utf-8') as f:
f.write(response.text)
print("Building footprints downloaded and saved to buildings.geojson")
else:
print(f"Error fetching data from Overpass API: {response.status_code}")
print(response.text)
exit()
# Step 4: Process the Retrieved GeoJSON to Add Latitude and Longitude Properties
with open('buildings.geojson') as f:
data = geojson.load(f)
def calculate_centroid(geometry):
geom_shape = shape(geometry)
centroid = geom_shape.centroid
return centroid.y, centroid.x # lat, lon
for feature in data['features']:
if 'center' in feature:
feature['properties']['lat'] = feature['center']['lat']
feature['properties']['lon'] = feature['center']['lon']
del feature['center']
elif feature['geometry']['type'] == 'Point':
lon, lat = feature['geometry']['coordinates']
feature['properties']['lat'] = lat
feature['properties']['lon'] = lon
else:
lat, lon = calculate_centroid(feature['geometry'])
feature['properties']['lat'] = lat
feature['properties']['lon'] = lon
with open('buildings_with_latlon.geojson', 'w') as f:
geojson.dump(data, f)
print("Processed GeoJSON saved to buildings_with_latlon.geojson")
Additional Considerations
Handling Large Areas:
For extensive urban areas, Overpass API queries might time out or fail due to size. Consider splitting the area into smaller bounding boxes and querying them sequentially.
Implement robust error handling to manage API failures, retries, and partial data retrieval.
Performance Optimization:
Simplify geometries where possible to reduce processing time and file sizes.
Alternative Data Sources:
Depending on your needs, consider using other OSM data extraction tools like osmnx which can simplify network-based queries and data retrieval.
Conclusion
The above script automates the entire process of extracting urbanized areas from a raster, querying building footprints from OSM within that area, and enriching the resulting GeoJSON with latitude and longitude properties. Adjust the population density threshold and other parameters as per your specific requirements.
Feel free to further customize the script to handle multiple urban polygons, different definitions of urbanization, or integrating additional data sources.