headless-studio / leptos-leaflet

MIT License
27 stars 18 forks source link

Removing Marker #38

Open siqpush opened 1 week ago

siqpush commented 1 week ago

Is it possible to remove a marker from the map based on some condition? I've banged my head a bit and my last attempt was something like the below. I am fairly sure this is not the right direction but thought it may help explain what I am trying to do.

create_effect(move |_| {
        if let Some(marker) = marker.get().map(|obj: Object| obj.unchecked_into::<Marker>()) {
            let pane = marker.get_pane();
            if let Some(element) = pane
                .get_elements_by_class_name("leaflet-marker-icon leaflet-zoom-animated leaflet-interactive leaflet-marker-draggable")
                .item(0)
            {
                if some_remove_marker_signal.get() {
                    pane.remove_child(&element).expect("failed to remove marker");
                }
            }
        }
    });

     view! {
              <Marker
                  position={Position::default()}
                  layer_events=LayerEvents::new()
                  .on_add(move |ev| {
                      marker.set_untracked(Some(ev.target()));
                  })
     }
otopetrik commented 1 week ago

This seems to work:


view! {
    <Show when=move || { some_remove_marker_signal.get() == false }>
        <Marker position=... > ... </Marker>
    </Show>
}
dgsantana commented 1 week ago

That is one way (the on_cleanup on the marker removes it from the map), another is to create/destroy the marker using the leaflet API. When I get some time I will create an example.

siqpush commented 6 days ago

thanks @otopetrik and @dgsantana - tried the Show approach earlier on and was having trouble. Almost appears as though the once the marker is bound to the map Show no longer has the ability to remove - could be a self inflicted reactive issue though.

I think the leaflet api approach would be super beneficial to gaining a better understanding.

dgsantana commented 5 days ago

@siqpush I added a very simple example that should get you started, it's here. There is an helper struct to handle the removal of the marker in this case when the struct is dropped. But this can be applied to any other type of leaflet. I build a line and point drawing system for leaflet in rust around this idea. You can also add events using this api.

siqpush commented 5 days ago

@dgsantana this is awesome - gave me much better insight insight into leaflet and how your api intertwines. Also, the IntoLatLng impl was a nice cherry on top! Thanks again.