svelte-maplibre
svelte-maplibre copied to clipboard
Add events to the map
Hello @dimfeld
I have more ideas 😊 !
I think it would be useful to add all the existing events on layer, on the map as well:
- click
- contextmenu
- dblclick
Thanks
I'll have more time to work on this later this week but in the meantime please feel free to file a PR.
On Tue Sep 5, 2023, 07:10 AM GMT, glops @.***> wrote:
Hello @dimfeld https://github.com/dimfeld I have more ideas 😊 ! I think it would be useful to add all the existing events on layer, on the map as well:
- click
- contextmenu
- dblclick Thanks — Reply to this email directly, view it on GitHub https://github.com/dimfeld/svelte-maplibre/issues/57, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAKOLVV77MP34R6KKF767UDXY3F43ANCNFSM6AAAAAA4LJSH7M. You are receiving this because you were mentioned.Message ID: @.***>
I'm curious if there are any ideas to make event handler management easier in Svelte. I'm currently doing map.on
and map.off
in onMount
and onDestroy
like this: https://github.com/acteng/atip/blob/1dff9d26015759e37cc382dba34defc9bf415c1a/src/lib/draw/route/SplitRouteMode.svelte#L27
This is often done from deep within some nested component, not directly in the place creating <MapLibre />
. It'd almost be nice to have some helper like <svelte:window on:keydown={onKeyDown} />
that can manage registration and handle cases where the map isn't loaded yet.
Off the top of my head, something like this would work:
function handleEvents(map: Readable<Map|null>, events: Record<string, (e: MapEvent) => void>) {
let $map: Map|null = null;
const addHandlers = (m: Map) => {
for(let [event, fn] of Object.entries(events)) {
m.on(event, fn);
}
}
const unsub = map.subscribe((m) => {
if(!$map) {
addHandlers(m);
}
$map = m;
});
onDestroy(() => {
unsub();
if(!$map) {
return;
}
for(let [event, fn] of Object.entries(events)) {
$map.off(event, fn);
}
});
}
Integrating it with the existing context structures would make it even easier since you wouldn't have to manually pass the map store.
I'm about to head out on vacation but would be happy to get something like this added when I'm back in early Novmber.
Just added #161 which lets you do things like <MapEvents on:click={clickHandler} />
from any component inside the MapLibre component. Need to do some testing and add a demo, probably on Thursday but maybe Friday.
Released in v0.9.2