Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing leaflet layers and L.marker method

I was wondering if anyone knows how or if you can actually remove a layer of points after adding them using this convention:

var pointsLayer, someFeatures = [{
            //Hard coded for now
            "type": "Feature",
            "properties": {
                "name": "Company A",
                "show_on_map": true,
                "icon": 'img/violations.png'
            },
            "geometry": {
                "type": "Point",
                "coordinates": [43.22519, -107.69348]
            }
        }, {
            "type": "Feature",
           .
           .
           .
   }];
for(w=0; w < someFeatures.length; w++){
                pointsLayer = L.marker(someFeatures[w].geometry.coordinates, {icon: violations})   
                    .bindPopup("Company: "+someFeatures[w].properties.name);
                    //add map points 
                    map.addLayer(pointsLayer);
            }

The typical removeLayer(pointsLayer); within a similar for loop does not work for me. But, that does not mean that there isn't a way to loop through. I am just not sure exactly how. I am trying to add points, which is working, and then remove them on an event (not working). Any ideas?

like image 286
Mr. Concolato Avatar asked Dec 23 '13 21:12

Mr. Concolato


People also ask

How do you remove markers from a layer leaflet?

Layergroup allows to control all markers at once. Ok, removing the layer seems to be the solution, but the more straightforward answer to the question, how to remove a marker is the one given by @HarijsKrūtainis : marker. remove() , it worked perfectly to me.

How do you delete a layer on a map in leaflet?

WMS tile layers are extensions of tile layers, so they can also be removed or cleared via removeTiles() or clearTiles() . leaflet documentation built on March 24, 2022, 1:05 a.m.

What is _leaflet_id?

_leaflet_id is an internal identifier that is set by Leaflet library when it needs it.


2 Answers

Instead of adding all markers directly on the map, you can add the markers on a separate layer (i.e. var markers = new L.FeatureGroup();) and then add that layer on the map (map.addLayer(markers);) outside the loop.

For example,

http://jsfiddle.net/9BXL7/

html

<button>remove all markers</button>
<div id="map"></div>

css

html, body, #map {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

js

var cloudmade = L.tileLayer('http://{s}.tile.cloudmade.com/{key}/997/256/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade',
    key: 'BC9A493B41014CAABB98F0471D759707'
});

var map = L.map('map')
    .setView([50.5, 30.51], 15)
    .addLayer(cloudmade);

var markers = new L.FeatureGroup();

function getRandomLatLng(map) {
    var bounds = map.getBounds(),
        southWest = bounds.getSouthWest(),
        northEast = bounds.getNorthEast(),
        lngSpan = northEast.lng - southWest.lng,
        latSpan = northEast.lat - southWest.lat;

    return new L.LatLng(
    southWest.lat + latSpan * Math.random(),
    southWest.lng + lngSpan * Math.random());
}

function populate() {
    for (var i = 0; i < 10; i++) {
        var marker = L.marker(getRandomLatLng(map));
        marker.bindPopup("<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.</p><p>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque.</p>", {
            showOnMouseOver: true
        });
        markers.addLayer(marker);
    }
    return false;
}

map.addLayer(markers);

populate();
function removeAllMarkers(){
    map.removeLayer(markers);
}
document.querySelector('button').onclick=function(){removeAllMarkers()};

Should you need to DELETE or clear the markers layer to swap out the points in the future use:

markers.clearLayers();
like image 127
melc Avatar answered Oct 19 '22 19:10

melc


Use map.removeLayer():

var circle = L.circle([lat, lng], 1000).addTo(map);
map.removeLayer(circle);
like image 22
f1lt3r Avatar answered Oct 19 '22 19:10

f1lt3r