Skip to content

Commit

Permalink
oncilck draft
Browse files Browse the repository at this point in the history
  • Loading branch information
Nour-Cheour10 committed Aug 26, 2024
1 parent 0c21a18 commit 052c71f
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 69 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ ehthumbs.db
# Folder config file
Desktop.ini
.config.ini
.env.ini


# Recycle Bin used on file shares
$RECYCLE.BIN/
Expand Down
6 changes: 6 additions & 0 deletions Untitled.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
97 changes: 31 additions & 66 deletions examples/RasterLayer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -19,118 +19,83 @@
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import configparser\n",
"config = configparser.ConfigParser()\n",
"config.read('.config.ini')\n",
"key = config['DEFAULT']['key']"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "bf54f7b270eb4c12ba2fbcaeea2583da",
"model_id": "b55d411654314ab094b4b12ea0055e9f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Map(center=[4.299875503991089, 46.85012303279379], zoom=0.0)"
"Map(center=[4.299875503991089, 46.85012303279379], layers=[RasterTileLayer()], zoom=0.0)"
]
},
"execution_count": 3,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"m = Map(center=[4.299875503991089, 46.85012303279379], zoom=0)\n",
"layer=RasterTileLayer()\n",
"m.add_layer(layer)\n",
"m"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"RasterTileLayer"
]
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"layere=RasterTileLayer()"
"import configparser\n",
"config = configparser.ConfigParser()\n",
"config.read('../.env.ini')\n",
"api_key = config['DEFAULT']['api_key']"
]
},
{
"cell_type": "code",
"execution_count": 5,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"m.add_layer(layere) "
"RasterTileLayer"
]
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"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",
"country_variable = None\n",
"def update_country_variable(lat, lon, country):\n",
" global country_variable\n",
" country_variable = country\n",
" print(f\"Updated country variable to: {country_variable}\")\n",
"\n",
"raster = RasterTileLayer(attributions=attributions,url='https://api.maptiler.com/maps/dataviz-dark/{z}/{x}/{y}.png?key=' + key,\n",
" tileSize= 512)\n",
"m.add_layer(raster) "
"# Enregistrer la fonction de rappel pour les clics\n",
"m.on_click(lambda lat, lon, country: update_country_variable(lat, lon, country), api_key)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"m.remove_layer(raster)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"attributions = [\n",
" '&copy; <a href=\"https://www.maptiler.com/copyright/\" target=\"_blank\">MapTiler</a>',\n",
" '&copy; <a href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\">OpenStreetMap contributors</a>'\n",
"]\n",
"\n",
"rasterlay = RasterTileLayer(url=f'https://api.maptiler.com/maps/satellite/{{z}}/{{x}}/{{y}}.jpg?key={key}',attributions=attributions,tileSize=512,maxZoom=20)\n",
"m.add_layer(rasterlay)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"France\n"
]
}
],
"source": [
"m.remove_layer(rasterlay)"
"print(country_variable)"
]
}
],
Expand All @@ -150,7 +115,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
"version": "3.12.4"
}
},
"nbformat": 4,
Expand Down
2 changes: 1 addition & 1 deletion examples/VectorTileLayer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
"version": "3.12.4"
}
},
"nbformat": 4,
Expand Down
75 changes: 74 additions & 1 deletion ipyopenlayers/Map.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
from ipywidgets import DOMWidget, Widget, widget_serialization
from traitlets import Unicode, List, Instance, CFloat, Bool, Dict, Int, Float
from ._frontend import module_name, module_version
import requests
import unicodedata
import configparser


def_loc = [0.0, 0.0]

Expand Down Expand Up @@ -166,4 +170,73 @@ def remove_control(self, control):


def clear_layers(self):
self.layers = []
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, api_key):
"""
Handle click events and trigger registered callbacks.
"""
print(f"Handling click event at Longitude: {lon}, Latitude: {lat}")
country = self.get_country_from_coordinates_geoapify(lat, lon, api_key)
self.clicked_country = country
print(f"Country: {country}")

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

def on_click(self, callback, api_key):
"""
Register a callback to handle click events on the map and pass the API key.
"""
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.get_country_from_coordinates_geoapify(lat, lon, api_key))

self.on_msg(handle_frontend_event)

def normalize_country_name(self, country_name):
normalized_name = country_name.split(' ')[0]
normalized_name = unicodedata.normalize('NFKD', normalized_name)
normalized_name = normalized_name.encode('ASCII', 'ignore').decode('utf-8')
return normalized_name

def get_country_from_coordinates_geoapify(self, lat, lon, api_key):
url = f"https://api.geoapify.com/v1/geocode/reverse?lat={lat}&lon={lon}&apiKey={api_key}"
response = requests.get(url)
data = response.json()
features = data.get('features', [])

if features:
first_feature = features[0]
properties = first_feature.get('properties', {})
country = properties.get('country', None)
if country:
normalized_name = country.split(' ')[0]
normalized_name = unicodedata.normalize('NFKD', normalized_name)
normalized_name = normalized_name.encode('ASCII', 'ignore').decode('utf-8')
return normalized_name
return "Unknown"
14 changes: 13 additions & 1 deletion src/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { LayerModel, LayerView } from './layer';
import { BaseOverlayModel, BaseOverlayView } from './baseoverlay';
import { BaseControlModel, BaseControlView } from './basecontrol';
import { ViewObjectEventTypes } from 'ol/View';

import MapBrowserEvent from 'ol/MapBrowserEvent';
import { Map } from 'ol';
import View from 'ol/View';
import 'ol/ol.css';
Expand Down Expand Up @@ -117,6 +117,10 @@ export class MapView extends DOMWidgetView {
layers: [],
});

this.map.on('click', (event: MapBrowserEvent<MouseEvent>) => {
this.handleMapClick(event);
});

this.map.getView().on('change:center', () => {
this.model.set('center', this.map.getView().getCenter());
this.model.save_changes();
Expand All @@ -138,6 +142,14 @@ export class MapView extends DOMWidgetView {
this.model.on('change:zoom', this.zoomChanged, this);
this.model.on('change:center', this.centerChanged, this);
}

handleMapClick(event: MapBrowserEvent<MouseEvent>) {
const coordinate = event.coordinate;
const [lon, lat] = coordinate;
this.model.set('clicked_position', [lon, lat]);
this.model.save_changes();
this.send({ lon, lat });
}
layersChanged() {
const layers = this.model.get('layers') as LayerModel[];
this.layerViews.update(layers);
Expand Down

0 comments on commit 052c71f

Please sign in to comment.