ipyleaflet icon indicating copy to clipboard operation
ipyleaflet copied to clipboard

Add event coordinates to GeoJSON message

Open lopezvoliver opened this issue 1 year ago • 1 comments

This pull request adds event coordinates to the message sent on click and mouseover on GeoJSON.ts.

For example, here we can open a popup on the feature clicked by the user (#1227):

ipyleaflet-popup-click-location

from ipyleaflet import Map, GeoJSON, Popup
from ipywidgets import HTML

# Create a map centered at a specific location
m = Map(center=(51.55, -0.09), zoom=10)

# Example GeoJSON data with two polygons
geojson_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 layer
geojson_layer = GeoJSON(data=geojson_data)

# Popup
popup = Popup(
    close_button=True,
    auto_close=False,
    auto_pan=False,
    close_on_escape_key=False
)

def on_click_handler(**kwargs):
    properties = kwargs["properties"]
    popup.child = HTML(properties["popup_content"])
    popup.location = kwargs["coordinates"]  # This is what this PR provides.
    popup.open_popup()

geojson_layer.on_click(on_click_handler)

m.add(popup)
m.add(geojson_layer)

lopezvoliver avatar Aug 25 '24 07:08 lopezvoliver