import streamlit as st | |
import folium | |
import folium.plugins | |
from streamlit_folium import st_folium | |
import json | |
# Set the map center and zoom level | |
MAP_CENTER = [35.6895, 139.6917] # Tokyo | |
ZOOM_LEVEL = 10 | |
# Create a folium map object | |
m = folium.Map(location=MAP_CENTER, zoom_start=ZOOM_LEVEL) | |
# Create a DrawControl object | |
dc = folium.plugins.Draw() | |
# Set the draw options to allow only polygons and rectangles | |
# dc.draw_options = { | |
# "polyline": False, | |
# "circle": False, | |
# "circlemarker": False, | |
# "marker": False, | |
# } | |
# Set the edit options to allow editing and deleting | |
dc.edit_options = { | |
"edit": True, | |
"remove": True, | |
} | |
# Add the DrawControl object to the map | |
m.add_child(dc) | |
# Define a JavaScript function to handle the draw events | |
draw_events = """ | |
function handleDrawEvent(e) { | |
// Get the type and layer of the drawn or edited feature | |
var type = e.layerType; | |
var layer = e.layer; | |
// If the feature is a polygon or a rectangle, get its geojson data | |
if (type === 'polygon' || type === 'rectangle') { | |
var geojson = layer.toGeoJSON(); | |
// Send the geojson data to Python via Streamlit | |
streamlit.setComponentValue(geojson); | |
} | |
} | |
""" | |
# Add the JavaScript function to the HTML header of the map | |
m.get_root().header.add_child(folium.Element(draw_events)) | |
# Register the JavaScript function to the draw:created and draw:edited events | |
m.add_child(folium.Element("map.on('draw:created', handleDrawEvent);")) | |
m.add_child(folium.Element("map.on('draw:edited', handleDrawEvent);")) | |
# Display the folium map using streamlit | |
st_folium(m) | |
# # Get the geojson data from Streamlit | |
# geojson = st_folium.get_value() | |
# # Display the geojson data using streamlit | |
# st.write(geojson) | |