You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is it possible to display popups for a GeoJSON layer at mouse clicked locations? It seems the event handler does not contain mouse clicked coordinates. One workaround is to use the polygon/polyline centroid, which is not ideal for a large feature where the popup shows up very far away from the mouse clicked location.
fromipyleafletimportMap, GeoJSON, Popupimportjsonfromshapely.geometryimportshapeimportipywidgetsaswidgets# Create a map centered at a specific locationm=Map(center=(51.55, -0.09), zoom=10)
# Example GeoJSON data with two polygonsgeojson_data= {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Polygon A",
"popup_content": "This is Polygon A."
},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-0.1, 51.5],
[-0.1, 51.6],
[-0.05, 51.6],
[-0.05, 51.5],
[-0.1, 51.5]
]]
}
},
{
"type": "Feature",
"properties": {
"name": "Polygon B",
"popup_content": "This is Polygon B."
},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-0.08, 51.48],
[-0.08, 51.52],
[-0.03, 51.52],
[-0.03, 51.48],
[-0.08, 51.48]
]]
}
}
]
}
# Create a GeoJSON layergeojson_layer=GeoJSON(data=geojson_data)
output=widgets.Output()
# Function to calculate the centroid of a polygondefcalculate_centroid(polygon_coordinates):
polygon=shape({
"type": "Polygon",
"coordinates": polygon_coordinates
})
centroid=polygon.centroidreturncentroid.y, centroid.x# Return as (lat, lon)# Define a function to handle the on-click eventdefon_click_handler(event, feature, **kwargs):
# Calculate the centroid of the polygoncentroid=calculate_centroid(feature['geometry']['coordinates'])
withoutput:
print(f"event: {event}")
print(f"kwargs: {kwargs}")
print(f"centroid: {centroid}")
print(f"properties: {feature['properties']['popup_content']}")
# Create a popup with the content from GeoJSON propertiespopup=Popup(
location=centroid,
child=widgets.HTML(feature['properties']['popup_content']),
close_button=False,
auto_close=True
)
# Add the popup to the mapm.add_layer(popup)
# Bind the click event to the GeoJSON layergeojson_layer.on_click(on_click_handler)
# Add the GeoJSON layer to the mapm.add_layer(geojson_layer)
# Display the mapm
The text was updated successfully, but these errors were encountered:
Is it possible to display popups for a GeoJSON layer at mouse clicked locations? It seems the event handler does not contain mouse clicked coordinates. One workaround is to use the polygon/polyline centroid, which is not ideal for a large feature where the popup shows up very far away from the mouse clicked location.
Reference issue: opengeos/leafmap#873
The text was updated successfully, but these errors were encountered: