-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatiments.py
More file actions
136 lines (106 loc) · 4.18 KB
/
Copy pathbatiments.py
File metadata and controls
136 lines (106 loc) · 4.18 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import os
import argparse
import requests
import geopandas as gpd
import pandas as pd
import folium
from pyproj import Transformer
from shapely.geometry import Point
from folium import LayerControl
def fetch_buildings(x: float, y: float, radius: float):
"""Fetch building features from Geoportail WFS within a bounding box."""
minx, miny = x - radius, y - radius
maxx, maxy = x + radius, y + radius
url = "https://data.geopf.fr/wfs/ows"
params = {
"service": "WFS",
"version": "1.1.0",
"request": "GetFeature",
"typename": "BDTOPO_V3:batiment",
"outputFormat": "application/json",
"srsname": "EPSG:3857",
"bbox": f"{minx},{miny},{maxx},{maxy},EPSG:3857",
}
response = requests.get(url, params=params)
response.raise_for_status()
return response.json()
def process_buildings(geojson: dict) -> gpd.GeoDataFrame:
"""Convert GeoJSON to GeoDataFrame and clean attributes."""
gdf = gpd.GeoDataFrame.from_features(geojson["features"], crs="EPSG:3857")
if "date_d_apparition" in gdf.columns:
gdf["annee_construction"] = pd.to_datetime(
gdf["date_d_apparition"], errors="coerce", format="%Y-%m-%dZ"
).dt.year.astype("Int64")
return gdf
def get_building_gdf(lat: float, lon: float, radius: float) -> gpd.GeoDataFrame:
"""Fetch and process buildings around a point."""
transformer = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
x, y = transformer.transform(lon, lat)
buildings_data = fetch_buildings(x, y, radius)
gdf = process_buildings(buildings_data)
gdf = gdf.to_crs("EPSG:2154")
gdf_polygon = gpd.GeoDataFrame(geometry=[Point(lon, lat)], crs="EPSG:4326").to_crs(
"EPSG:2154"
)
gdf_polygon["geometry"] = gdf_polygon["geometry"].buffer(radius)
len_before = len(gdf)
gdf = gpd.sjoin(gdf, gdf_polygon, how="inner", predicate="within")
gdf = gdf.reset_index(drop=True).drop(columns=["index_right"])
len_after = len(gdf)
print(f"Removed {len_before - len_after} buildings outside the polygon.")
return gdf
def get_building_map(gdf: gpd.GeoDataFrame, column: str):
"""Generate a folium map from a GeoDataFrame colored by a given column."""
tiles = folium.TileLayer(
tiles="https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}",
attr="Google",
name="Google Satellite",
overlay=False,
control=True,
max_zoom=25,
)
m = gdf.explore(
column=column,
cmap="jet",
tiles="OpenStreetMap",
popup=False,
name="GeoDataframe",
)
tiles.add_to(m)
LayerControl().add_to(m)
return m
def main():
parser = argparse.ArgumentParser(
description="Fetch building data from Geoportail and generate maps."
)
parser.add_argument(
"--lat", type=float, required=True, help="Latitude in EPSG:4326"
)
parser.add_argument(
"--lon", type=float, required=True, help="Longitude in EPSG:4326"
)
parser.add_argument("--radius", type=float, required=True, help="Radius in meters")
parser.add_argument("--output", type=str, required=True, help="Output folder path")
args = parser.parse_args()
lat, lon, radius, output = args.lat, args.lon, args.radius, args.output
os.makedirs(output, exist_ok=True)
print("Fetching building data...")
gdf = get_building_gdf(lat, lon, radius)
gpkg_path = os.path.join(output, "batiments.gpkg")
print(f"Saving GeoPackage to {gpkg_path}")
gdf.to_file(gpkg_path, driver="GPKG")
if "hauteur" in gdf.columns:
print("Generating height map...")
m1 = get_building_map(gdf, column="hauteur")
m1.save(os.path.join(output, "buildings_hauteur.html"))
else:
print("⚠️ No 'hauteur' column found in data, skipping height map.")
if "annee_construction" in gdf.columns:
print("Generating construction year map...")
m2 = get_building_map(gdf, column="annee_construction")
m2.save(os.path.join(output, "buildings_annee.html"))
else:
print("⚠️ No 'annee_construction' column found in data, skipping year map.")
print("✅ All done!")
if __name__ == "__main__":
main()