dimfeld / svelte-maplibre

Svelte bindings for the MapLibre mapping library
https://svelte-maplibre.vercel.app
MIT License
319 stars 40 forks source link

Add events to the map #57

Closed glops closed 4 months ago

glops commented 1 year ago

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:

Thanks

dimfeld commented 1 year ago

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:

dabreegster commented 11 months ago

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.

dimfeld commented 11 months ago

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 commented 5 months ago

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 commented 4 months ago

Released in v0.9.2