svelte-maplibre icon indicating copy to clipboard operation
svelte-maplibre copied to clipboard

Add events to the map

Open glops opened this issue 1 year ago • 4 comments

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

glops avatar Sep 05 '23 07:09 glops

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:

dimfeld avatar Sep 05 '23 07:09 dimfeld

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.

dabreegster avatar Oct 23 '23 15:10 dabreegster

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.

dimfeld avatar Oct 23 '23 23:10 dimfeld

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.

dimfeld avatar May 02 '24 09:05 dimfeld

Released in v0.9.2

dimfeld avatar May 11 '24 00:05 dimfeld