Skip to content

Commit 052c71f

Browse files
committed
oncilck draft
1 parent 0c21a18 commit 052c71f

File tree

6 files changed

+127
-69
lines changed

6 files changed

+127
-69
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ ehthumbs.db
129129
# Folder config file
130130
Desktop.ini
131131
.config.ini
132+
.env.ini
133+
132134

133135
# Recycle Bin used on file shares
134136
$RECYCLE.BIN/

Untitled.ipynb

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"cells": [],
3+
"metadata": {},
4+
"nbformat": 4,
5+
"nbformat_minor": 5
6+
}

examples/RasterLayer.ipynb

+31-66
Original file line numberDiff line numberDiff line change
@@ -19,118 +19,83 @@
1919
{
2020
"cell_type": "code",
2121
"execution_count": 2,
22-
"metadata": {},
23-
"outputs": [],
24-
"source": [
25-
"import configparser\n",
26-
"config = configparser.ConfigParser()\n",
27-
"config.read('.config.ini')\n",
28-
"key = config['DEFAULT']['key']"
29-
]
30-
},
31-
{
32-
"cell_type": "code",
33-
"execution_count": 3,
3422
"metadata": {
3523
"scrolled": true
3624
},
3725
"outputs": [
3826
{
3927
"data": {
4028
"application/vnd.jupyter.widget-view+json": {
41-
"model_id": "bf54f7b270eb4c12ba2fbcaeea2583da",
29+
"model_id": "b55d411654314ab094b4b12ea0055e9f",
4230
"version_major": 2,
4331
"version_minor": 0
4432
},
4533
"text/plain": [
46-
"Map(center=[4.299875503991089, 46.85012303279379], zoom=0.0)"
34+
"Map(center=[4.299875503991089, 46.85012303279379], layers=[RasterTileLayer()], zoom=0.0)"
4735
]
4836
},
49-
"execution_count": 3,
37+
"execution_count": 2,
5038
"metadata": {},
5139
"output_type": "execute_result"
5240
}
5341
],
5442
"source": [
5543
"m = Map(center=[4.299875503991089, 46.85012303279379], zoom=0)\n",
44+
"layer=RasterTileLayer()\n",
45+
"m.add_layer(layer)\n",
5646
"m"
5747
]
5848
},
59-
{
60-
"cell_type": "markdown",
61-
"metadata": {},
62-
"source": [
63-
"RasterTileLayer"
64-
]
65-
},
6649
{
6750
"cell_type": "code",
68-
"execution_count": 4,
51+
"execution_count": 5,
6952
"metadata": {},
7053
"outputs": [],
7154
"source": [
72-
"layere=RasterTileLayer()"
55+
"import configparser\n",
56+
"config = configparser.ConfigParser()\n",
57+
"config.read('../.env.ini')\n",
58+
"api_key = config['DEFAULT']['api_key']"
7359
]
7460
},
7561
{
76-
"cell_type": "code",
77-
"execution_count": 5,
62+
"cell_type": "markdown",
7863
"metadata": {},
79-
"outputs": [],
8064
"source": [
81-
"m.add_layer(layere) "
65+
"RasterTileLayer"
8266
]
8367
},
8468
{
8569
"cell_type": "code",
86-
"execution_count": 26,
70+
"execution_count": 6,
8771
"metadata": {},
8872
"outputs": [],
8973
"source": [
90-
"attributions = '<a href=\"https://www.maptiler.com/copyright/\" target=\"_blank\">&copy; MapTiler</a> ' +'<a href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\">&copy; OpenStreetMap contributors</a>';\n",
74+
"country_variable = None\n",
75+
"def update_country_variable(lat, lon, country):\n",
76+
" global country_variable\n",
77+
" country_variable = country\n",
78+
" print(f\"Updated country variable to: {country_variable}\")\n",
9179
"\n",
92-
"raster = RasterTileLayer(attributions=attributions,url='https://api.maptiler.com/maps/dataviz-dark/{z}/{x}/{y}.png?key=' + key,\n",
93-
" tileSize= 512)\n",
94-
"m.add_layer(raster) "
80+
"# Enregistrer la fonction de rappel pour les clics\n",
81+
"m.on_click(lambda lat, lon, country: update_country_variable(lat, lon, country), api_key)"
9582
]
9683
},
9784
{
9885
"cell_type": "code",
9986
"execution_count": 8,
100-
"metadata": {
101-
"scrolled": true
102-
},
103-
"outputs": [],
104-
"source": [
105-
"m.remove_layer(raster)"
106-
]
107-
},
108-
{
109-
"cell_type": "code",
110-
"execution_count": 9,
111-
"metadata": {
112-
"jupyter": {
113-
"source_hidden": true
114-
}
115-
},
116-
"outputs": [],
117-
"source": [
118-
"attributions = [\n",
119-
" '&copy; <a href=\"https://www.maptiler.com/copyright/\" target=\"_blank\">MapTiler</a>',\n",
120-
" '&copy; <a href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\">OpenStreetMap contributors</a>'\n",
121-
"]\n",
122-
"\n",
123-
"rasterlay = RasterTileLayer(url=f'https://api.maptiler.com/maps/satellite/{{z}}/{{x}}/{{y}}.jpg?key={key}',attributions=attributions,tileSize=512,maxZoom=20)\n",
124-
"m.add_layer(rasterlay)"
125-
]
126-
},
127-
{
128-
"cell_type": "code",
129-
"execution_count": 11,
13087
"metadata": {},
131-
"outputs": [],
88+
"outputs": [
89+
{
90+
"name": "stdout",
91+
"output_type": "stream",
92+
"text": [
93+
"France\n"
94+
]
95+
}
96+
],
13297
"source": [
133-
"m.remove_layer(rasterlay)"
98+
"print(country_variable)"
13499
]
135100
}
136101
],
@@ -150,7 +115,7 @@
150115
"name": "python",
151116
"nbconvert_exporter": "python",
152117
"pygments_lexer": "ipython3",
153-
"version": "3.10.14"
118+
"version": "3.12.4"
154119
}
155120
},
156121
"nbformat": 4,

examples/VectorTileLayer.ipynb

+1-1
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@
321321
"name": "python",
322322
"nbconvert_exporter": "python",
323323
"pygments_lexer": "ipython3",
324-
"version": "3.10.14"
324+
"version": "3.12.4"
325325
}
326326
},
327327
"nbformat": 4,

ipyopenlayers/Map.py

+74-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010
from ipywidgets import DOMWidget, Widget, widget_serialization
1111
from traitlets import Unicode, List, Instance, CFloat, Bool, Dict, Int, Float
1212
from ._frontend import module_name, module_version
13+
import requests
14+
import unicodedata
15+
import configparser
16+
1317

1418
def_loc = [0.0, 0.0]
1519

@@ -166,4 +170,73 @@ def remove_control(self, control):
166170

167171

168172
def clear_layers(self):
169-
self.layers = []
173+
self.layers = []
174+
175+
def on_msg(self, callback):
176+
"""Register a callback for receiving messages from the frontend."""
177+
self._msg_callback = callback
178+
179+
def _handle_msg(self, msg):
180+
"""Handle a message received from the frontend."""
181+
if hasattr(self, '_msg_callback'):
182+
content = msg.get('content', {})
183+
buffers = msg.get('buffers', [])
184+
self._msg_callback(self, content, buffers)
185+
186+
def _handle_click(self, lat, lon, api_key):
187+
"""
188+
Handle click events and trigger registered callbacks.
189+
"""
190+
print(f"Handling click event at Longitude: {lon}, Latitude: {lat}")
191+
country = self.get_country_from_coordinates_geoapify(lat, lon, api_key)
192+
self.clicked_country = country
193+
print(f"Country: {country}")
194+
195+
callbacks = self._click_callbacks.get_callbacks() if self._click_callbacks else []
196+
for callback in callbacks:
197+
if callable(callback):
198+
callback(lat, lon, country)
199+
200+
def on_click(self, callback, api_key):
201+
"""
202+
Register a callback to handle click events on the map and pass the API key.
203+
"""
204+
self._click_callback = callback
205+
206+
def handle_frontend_event(widget, content, buffers):
207+
"""Handle the click event from the frontend."""
208+
data = content.get('data', {})
209+
method = data.get('method', '')
210+
211+
if method == 'custom':
212+
event_data = data.get('content', {})
213+
lon = event_data.get('lon')
214+
lat = event_data.get('lat')
215+
216+
if callable(self._click_callback):
217+
self._click_callback(lat, lon, self.get_country_from_coordinates_geoapify(lat, lon, api_key))
218+
219+
self.on_msg(handle_frontend_event)
220+
221+
def normalize_country_name(self, country_name):
222+
normalized_name = country_name.split(' ')[0]
223+
normalized_name = unicodedata.normalize('NFKD', normalized_name)
224+
normalized_name = normalized_name.encode('ASCII', 'ignore').decode('utf-8')
225+
return normalized_name
226+
227+
def get_country_from_coordinates_geoapify(self, lat, lon, api_key):
228+
url = f"https://api.geoapify.com/v1/geocode/reverse?lat={lat}&lon={lon}&apiKey={api_key}"
229+
response = requests.get(url)
230+
data = response.json()
231+
features = data.get('features', [])
232+
233+
if features:
234+
first_feature = features[0]
235+
properties = first_feature.get('properties', {})
236+
country = properties.get('country', None)
237+
if country:
238+
normalized_name = country.split(' ')[0]
239+
normalized_name = unicodedata.normalize('NFKD', normalized_name)
240+
normalized_name = normalized_name.encode('ASCII', 'ignore').decode('utf-8')
241+
return normalized_name
242+
return "Unknown"

src/widget.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { LayerModel, LayerView } from './layer';
1111
import { BaseOverlayModel, BaseOverlayView } from './baseoverlay';
1212
import { BaseControlModel, BaseControlView } from './basecontrol';
1313
import { ViewObjectEventTypes } from 'ol/View';
14-
14+
import MapBrowserEvent from 'ol/MapBrowserEvent';
1515
import { Map } from 'ol';
1616
import View from 'ol/View';
1717
import 'ol/ol.css';
@@ -117,6 +117,10 @@ export class MapView extends DOMWidgetView {
117117
layers: [],
118118
});
119119

120+
this.map.on('click', (event: MapBrowserEvent<MouseEvent>) => {
121+
this.handleMapClick(event);
122+
});
123+
120124
this.map.getView().on('change:center', () => {
121125
this.model.set('center', this.map.getView().getCenter());
122126
this.model.save_changes();
@@ -138,6 +142,14 @@ export class MapView extends DOMWidgetView {
138142
this.model.on('change:zoom', this.zoomChanged, this);
139143
this.model.on('change:center', this.centerChanged, this);
140144
}
145+
146+
handleMapClick(event: MapBrowserEvent<MouseEvent>) {
147+
const coordinate = event.coordinate;
148+
const [lon, lat] = coordinate;
149+
this.model.set('clicked_position', [lon, lat]);
150+
this.model.save_changes();
151+
this.send({ lon, lat });
152+
}
141153
layersChanged() {
142154
const layers = this.model.get('layers') as LayerModel[];
143155
this.layerViews.update(layers);

0 commit comments

Comments
 (0)