MapLibre Map Clicked Attribute Example¶
This example demonstrates how to use the clicked
attribute of MapLibreMap to capture map click coordinates.
In [1]:
Copied!
from anymap.maplibre import MapLibreMap
import ipywidgets as widgets
from IPython.display import display
from anymap.maplibre import MapLibreMap
import ipywidgets as widgets
from IPython.display import display
In [2]:
Copied!
# Create a MapLibre map
m = MapLibreMap(center=[-122.4194, 37.7749], zoom=10, style="streets") # San Francisco
m
# Create a MapLibre map
m = MapLibreMap(center=[-122.4194, 37.7749], zoom=10, style="streets") # San Francisco
m
Out[2]:
In [3]:
Copied!
# Create a widget to display clicked coordinates
output = widgets.Output()
def on_map_clicked(change):
clicked_coords = change["new"]
if clicked_coords: # Check if not empty
with output:
output.clear_output()
print(f"Map clicked at: {clicked_coords}")
print(f"Longitude: {clicked_coords.get('lng', 'N/A')}")
print(f"Latitude: {clicked_coords.get('lat', 'N/A')}")
# Observe changes to the clicked attribute
m.observe(on_map_clicked, names="clicked")
display(output)
# Create a widget to display clicked coordinates
output = widgets.Output()
def on_map_clicked(change):
clicked_coords = change["new"]
if clicked_coords: # Check if not empty
with output:
output.clear_output()
print(f"Map clicked at: {clicked_coords}")
print(f"Longitude: {clicked_coords.get('lng', 'N/A')}")
print(f"Latitude: {clicked_coords.get('lat', 'N/A')}")
# Observe changes to the clicked attribute
m.observe(on_map_clicked, names="clicked")
display(output)
In [4]:
Copied!
# You can also access the clicked coordinates directly
print("Current clicked coordinates:", m.clicked)
# The clicked attribute returns a dict with 'lng' and 'lat' keys
# Example: {'lng': -122.34567890, 'lat': 37.1234567890}
# You can also access the clicked coordinates directly
print("Current clicked coordinates:", m.clicked)
# The clicked attribute returns a dict with 'lng' and 'lat' keys
# Example: {'lng': -122.34567890, 'lat': 37.1234567890}
Current clicked coordinates: {}
Instructions¶
- Click anywhere on the map above
- The coordinates will be displayed in the output widget
- The
m.clicked
attribute will contain the latest click coordinates as a dictionary withlng
andlat
keys - You can observe changes to the
clicked
attribute usingm.observe(callback, names='clicked')