Vertdure commited on
Commit
b6b6ea7
•
1 Parent(s): 91c174c

Update pages/12_🌲_VertXtractor.py

Browse files
Files changed (1) hide show
  1. pages/12_🌲_VertXtractor.py +54 -54
pages/12_🌲_VertXtractor.py CHANGED
@@ -4,9 +4,8 @@ import folium
4
  from streamlit_folium import folium_static, st_folium
5
  from folium.plugins import Draw
6
  import requests
7
- from io import BytesIO
8
- from PIL import Image
9
  from shapely.geometry import box
 
10
 
11
  # Liste des couches disponibles
12
  LAYERS = {
@@ -30,20 +29,12 @@ def draw_box_on_map():
30
  edit_options={'edit': False}
31
  )
32
  draw.add_to(m)
33
-
34
- output = st_folium(m, width=700, height=500)
35
-
36
- if output['last_active_drawing']:
37
- coords = output['last_active_drawing']['geometry']['coordinates'][0]
38
- return box(min(c[0] for c in coords), min(c[1] for c in coords),
39
- max(c[0] for c in coords), max(c[1] for c in coords))
40
- return None
41
 
42
  def create_geojson_from_box(bbox):
43
  gdf = gpd.GeoDataFrame({'geometry': [bbox]}, crs="EPSG:4326")
44
  gdf_swiss = gdf.to_crs("EPSG:2056")
45
- gdf['geometry_swiss'] = gdf_swiss['geometry']
46
- return gdf
47
 
48
  def extract_swisstopo_data(bbox, layer_id):
49
  api_url = f"https://data.geo.admin.ch/api/stac/v0.9/collections/{layer_id}/items"
@@ -65,51 +56,60 @@ def extract_esri_data(bbox, layer_id):
65
  def main():
66
  st.title("Extracteur de donnĂ©es Swisstopo et ESRI")
67
 
68
- # Étape 1: Dessiner la boîte de sélection
69
- st.subheader("Étape 1: Dessiner la zone d'intérêt")
70
- bbox = draw_box_on_map()
71
-
72
- if bbox:
73
- st.success("Zone sélectionnée avec succès!")
74
- gdf = create_geojson_from_box(bbox)
75
-
76
- # Affichage de la carte avec la boîte dessinée
77
- m = folium.Map()
78
- folium.GeoJson(gdf).add_to(m)
79
- m.fit_bounds(m.get_bounds())
80
- folium_static(m)
81
-
82
- # Étape 2: Sélection des couches
83
- st.subheader("Étape 2: Sélection des couches")
 
 
 
 
 
 
 
 
 
 
 
84
  selected_layers = st.multiselect("SĂ©lectionnez les couches Ă  extraire", list(LAYERS.keys()))
85
 
86
  if st.button("Extraire les donnĂ©es"):
87
- for layer_name in selected_layers:
88
- layer_info = LAYERS[layer_name]
89
-
90
- # Choix des coordonnées en fonction de la source
91
- if layer_info["source"] == "swisstopo":
92
- bbox = gdf['geometry_swiss'].total_bounds
93
- else: # ESRI
94
- bbox = gdf['geometry'].total_bounds
95
-
96
- st.write(f"Extraction de {layer_name}...")
97
-
98
- if layer_info["source"] == "swisstopo":
99
- data = extract_swisstopo_data(bbox, layer_info["id"])
100
- else:
101
- data = extract_esri_data(bbox, layer_info["id"])
102
-
103
- if data is not None:
104
- st.write(data.head())
105
- st.download_button(
106
- label=f"Télécharger {layer_name} (GeoJSON)",
107
- data=data.to_json(),
108
- file_name=f"{layer_name.lower().replace(' ', '_')}.geojson",
109
- mime="application/json"
110
- )
111
- else:
112
- st.warning(f"Aucune donnée trouvée pour {layer_name}")
113
 
114
  st.sidebar.markdown("## Ă€ propos")
115
  st.sidebar.markdown("Cet outil permet d'extraire des donnĂ©es gĂ©ospatiales de Swisstopo et ESRI.")
 
4
  from streamlit_folium import folium_static, st_folium
5
  from folium.plugins import Draw
6
  import requests
 
 
7
  from shapely.geometry import box
8
+ import json
9
 
10
  # Liste des couches disponibles
11
  LAYERS = {
 
29
  edit_options={'edit': False}
30
  )
31
  draw.add_to(m)
32
+ return st_folium(m, width=700, height=500)
 
 
 
 
 
 
 
33
 
34
  def create_geojson_from_box(bbox):
35
  gdf = gpd.GeoDataFrame({'geometry': [bbox]}, crs="EPSG:4326")
36
  gdf_swiss = gdf.to_crs("EPSG:2056")
37
+ return json.loads(gdf.to_json()), json.loads(gdf_swiss.to_json())
 
38
 
39
  def extract_swisstopo_data(bbox, layer_id):
40
  api_url = f"https://data.geo.admin.ch/api/stac/v0.9/collections/{layer_id}/items"
 
56
  def main():
57
  st.title("Extracteur de donnĂ©es Swisstopo et ESRI")
58
 
59
+ col1, col2 = st.columns([2, 1])
60
+
61
+ with col1:
62
+ st.subheader("Étape 1: Définir la zone d'intérêt")
63
+ method = st.radio("Choisissez une méthode", ["Dessiner sur la carte", "Charger un GeoJSON"])
64
+
65
+ if method == "Dessiner sur la carte":
66
+ map_data = draw_box_on_map()
67
+ if map_data['last_active_drawing']:
68
+ coords = map_data['last_active_drawing']['geometry']['coordinates'][0]
69
+ bbox = box(min(c[0] for c in coords), min(c[1] for c in coords),
70
+ max(c[0] for c in coords), max(c[1] for c in coords))
71
+ geojson_wgs84, geojson_swiss = create_geojson_from_box(bbox)
72
+ st.session_state['geojson_wgs84'] = geojson_wgs84
73
+ st.session_state['geojson_swiss'] = geojson_swiss
74
+ st.success("Zone sélectionnée avec succès!")
75
+
76
+ else:
77
+ uploaded_file = st.file_uploader("Chargez votre GeoJSON", type="geojson")
78
+ if uploaded_file:
79
+ gdf = gpd.read_file(uploaded_file)
80
+ st.session_state['geojson_wgs84'] = json.loads(gdf.to_crs(4326).to_json())
81
+ st.session_state['geojson_swiss'] = json.loads(gdf.to_crs(2056).to_json())
82
+ st.success("GeoJSON chargé avec succès!")
83
+
84
+ with col2:
85
+ st.subheader("Étape 2: Sélectionner les couches")
86
  selected_layers = st.multiselect("SĂ©lectionnez les couches Ă  extraire", list(LAYERS.keys()))
87
 
88
  if st.button("Extraire les donnĂ©es"):
89
+ if 'geojson_wgs84' not in st.session_state or 'geojson_swiss' not in st.session_state:
90
+ st.error("Veuillez d'abord définir une zone d'intérêt.")
91
+ else:
92
+ for layer_name in selected_layers:
93
+ layer_info = LAYERS[layer_name]
94
+
95
+ if layer_info["source"] == "swisstopo":
96
+ bbox = gpd.GeoDataFrame.from_features(st.session_state['geojson_swiss']).total_bounds
97
+ data = extract_swisstopo_data(bbox, layer_info["id"])
98
+ else: # ESRI
99
+ bbox = gpd.GeoDataFrame.from_features(st.session_state['geojson_wgs84']).total_bounds
100
+ data = extract_esri_data(bbox, layer_info["id"])
101
+
102
+ if data is not None:
103
+ st.write(f"Données extraites pour {layer_name}:")
104
+ st.write(data.head())
105
+ st.download_button(
106
+ label=f"Télécharger {layer_name} (GeoJSON)",
107
+ data=data.to_json(),
108
+ file_name=f"{layer_name.lower().replace(' ', '_')}.geojson",
109
+ mime="application/json"
110
+ )
111
+ else:
112
+ st.warning(f"Aucune donnée trouvée pour {layer_name}")
 
 
113
 
114
  st.sidebar.markdown("## Ă€ propos")
115
  st.sidebar.markdown("Cet outil permet d'extraire des donnĂ©es gĂ©ospatiales de Swisstopo et ESRI.")