Skip to content

Commit

Permalink
changed on click
Browse files Browse the repository at this point in the history
  • Loading branch information
Nour-Cheour10 committed Aug 26, 2024
1 parent 432f40c commit a594e1e
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 59 deletions.
3 changes: 3 additions & 0 deletions docs/source/_static/embed-bundle.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions docs/source/_static/embed-bundle.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/RasterLayer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.19"
"version": "3.12.4"
}
},
"nbformat": 4,
Expand Down
41 changes: 31 additions & 10 deletions examples/map.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 1,
"id": "94284d6e",
"metadata": {
"vscode": {
Expand All @@ -21,15 +21,15 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d279d658374d48db8f6a0459ccdba5e1",
"model_id": "ddc2f32ae8ce49c7b79b26a3e9ab4f85",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Map(center=[0.0, 0.0], layers=[RasterTileLayer()])"
"Map(center=[0.0, 0.0], zoom=2.0)"
]
},
"execution_count": 7,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -46,7 +46,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 2,
"id": "6ecd0ff6-93f3-4cd8-bc0a-8520aab07a84",
"metadata": {},
"outputs": [],
Expand All @@ -59,31 +59,52 @@
},
{
"cell_type": "code",
"execution_count": 9,
"id": "9ec9cfaa-9f30-4aef-a817-3ef1143d8004",
"execution_count": 3,
"id": "c2a997b5-3f80-4e9c-8956-5dba704f7eae",
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"import unicodedata\n",
"import configparser\n",
"\n",
"\n",
"def get_country_from_coordinates_geoapify(lat, lon): \n",
"def get_country_from_coordinates_geoapify(**kwargs):\n",
" # Extract latitude and longitude from kwargs\n",
" lon = kwargs.get('lon')\n",
" lat = kwargs.get('lat')\n",
" if lon is None or lat is None:\n",
" print(\"Latitude and longitude must be provided.\")\n",
" return\n",
" \n",
" # Define Geoapify API URL\n",
" url = f\"https://api.geoapify.com/v1/geocode/reverse?lat={lat}&lon={lon}&apiKey={api_key}\"\n",
" \n",
" # Make the API request\n",
" response = requests.get(url)\n",
" data = response.json()\n",
" \n",
" # Extract country from the API response\n",
" features = data.get('features', [])\n",
"\n",
" if features:\n",
" first_feature = features[0]\n",
" properties = first_feature.get('properties', {})\n",
" country = properties.get('country', None)\n",
" normalized_name = country.split(' ')[0]\n",
" normalized_name = unicodedata.normalize('NFKD', normalized_name)\n",
" normalized_name = normalized_name.encode('ASCII', 'ignore').decode('utf-8')\n",
" print(normalized_name)\n",
" print(f\"Country: {normalized_name}\")\n",
"\n",
"m.on_click(get_country_from_coordinates_geoapify)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "94b36482-ce0c-406f-8da9-46d6c4896000",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
Expand Down
61 changes: 14 additions & 47 deletions ipyopenlayers/openlayers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
# Copyright (c) QuantStack.
# Distributed under the terms of the Modified BSD License.

from ipywidgets import DOMWidget, Widget, widget_serialization
from ipywidgets import DOMWidget, Widget, widget_serialization, CallbackDispatcher

from traitlets import Unicode, List, Instance, CFloat, Bool, Dict, Int, Float
from ._frontend import module_name, module_version
import requests
Expand Down Expand Up @@ -46,7 +47,7 @@ class TileLayer(Layer):
Additional format options for the tile source.
"""

url = Unicode('').tag(sync=True)
url = Unicode('https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png').tag(sync=True)
attribution = Unicode("").tag(sync=True)
opacity = Float(1.0, min=0.0, max=1.0).tag(sync=True)
visible = Bool(True).tag(sync=True)
Expand Down Expand Up @@ -266,6 +267,8 @@ class Map(DOMWidget):
layers = List(Instance(Layer)).tag(sync=True, **widget_serialization)
overlays=List(Instance(BaseOverlay)).tag(sync=True, **widget_serialization)
controls=List(Instance(BaseControl)).tag(sync=True, **widget_serialization)
_click_callbacks = Instance(CallbackDispatcher, ())




Expand All @@ -280,6 +283,7 @@ def __init__(self, center=None, zoom=None, **kwargs):
The initial zoom level of the map.
"""
super().__init__(**kwargs)
self.on_msg(self._handle_mouse_events)
if center is not None:
self.center = center
if zoom is not None:
Expand Down Expand Up @@ -356,54 +360,17 @@ def clear_layers(self):
"""
self.layers = []

def on_msg(self, callback):
"""Register a callback for receiving messages from the frontend."""
self._msg_callback = callback

def _handle_msg(self, msg):
"""Handle a message received from the frontend."""
if hasattr(self, '_msg_callback'):
content = msg.get('content', {})
buffers = msg.get('buffers', [])
self._msg_callback(self, content, buffers)

def _handle_click(self, lat, lon):
"""Handle click events and trigger registered callbacks."""


callbacks = self._click_callbacks.get_callbacks()
for callback in callbacks:
if callable(callback):
callback(lat, lon)

def on_click(self, callback):
def _handle_mouse_events(self, _, content, buffers):
"""Handle mouse events and trigger click callbacks.
"""
Register a callback to handle click events on the map.
event_type = content.get("type", "")
if event_type == "click":
self._click_callbacks(**content)

Parameters
----------
callback : function
Function that accepts two arguments: lon (longitude) and lat (latitude) of the clicked position.
def on_click(self, callback, remove=False):
"""Add a click event listener.
"""
self._click_callbacks.register_callback(callback, remove=remove)

self._click_callback = callback


def handle_frontend_event(widget, content, buffers):
"""Handle the click event from the frontend."""
data = content.get('data', {})
method = data.get('method', '')


if method == 'custom':
event_data = data.get('content', {})
lon = event_data.get('lon')
lat = event_data.get('lat')

if callable(self._click_callback):
self._click_callback(lat, lon)

self.on_msg(handle_frontend_event)


2 changes: 1 addition & 1 deletion src/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export class MapView extends DOMWidgetView {
handleMapClick(event: MapBrowserEvent<MouseEvent>) {
const coordinate = event.coordinate;
const [lon, lat] = coordinate;
this.send({ lon, lat });
this.send({ type: 'click', lon, lat });
}
layersChanged() {
const layers = this.model.get('layers') as LayerModel[];
Expand Down

0 comments on commit a594e1e

Please sign in to comment.