0
votes

I have created Polygon Map using react-leaflet. I able to create it and also able to create markers selected in the multiselect dropdown on the map.However, i am unable to remove the selected marker [or any markers] for that matter. I am providing the code below which is divides into initializationMap method which would create initialize the map and later part iis updateMakers which is used to set new markers on Map which it is doing. My problem is to remove the marker on the map. I am new to leaflet and doesn't what am i missing. I tried to create a "markers" layers but is not helping me. Please help. Thanks!

var map = new L.Map('polygonMap'); //Initialization of Map
var markers = new L.FeatureGroup().addTo(map); // Creating a Feature Layer

I am adding markers using markers.addLayer(marker1); which works, However if i am iterating over the markers and than try to remove it , i am unable to do it. Please help, i am new to leaflet. TIA

2
Can you show how you iterate. The mistake is likely there. - YaFred
So whenever a option is selected from the dropdown to remove an element. I make flag true and remove using markerLayer.clearLayers() and polygonLayer.clearLayers(). I am adding markers using markerLayer.addLayer(marker); Can you tell me how can i remove all markers and than put markers that in the list props? - Rahul

2 Answers

0
votes

if marker1 is the marker layer object you want to remove, use the removeLayer function from the featureGroup.

See https://leafletjs.com/reference-1.5.0.html#featuregroup-removelayer

Your featureGroup is called markers, so it would be :

markers.removeLayer(marker1)
0
votes

After hours and hours trying to find out any solution i just figured it out this, i mean hide or show markers using react leaflet.

i can set classname (class) on the marker object or dependency/helper which ever is the solution selected. In my solution i was using custom icons on the markers so i defined a custom

L.icon({
                    iconUrl: ...,className: `marker-icon-route`...})

then on any event or onclick implemented what i just did is via document.querySelectorAll i loop through all elements within the map which contains the class mentioned marker-icon-route, just process a document queryselector

document.querySelectorAll('.marker-icon-route').forEach(e => e.style.display = 'none'); 

for the other hand if you want to show the markers just

 document.querySelectorAll('.marker-icon-route').forEach(e => e.style.display = 'block'); 

... this solution can be used for another helpers provided by leaflet-react such as polylines, poligones etc. Sorry for my English and i hope than my humble solution can help any developer frustrated as i was all this hours.