移除leaflet图层和L.marker方法

17
我想知道是否有人知道如何在使用这种约定添加点后,实际上是否可以删除一层点。
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);
            }

类似的 for 循环中典型的 removeLayer(pointsLayer) 对我不起作用。但是,这并不意味着没有遍历的方法。我只是不确定具体如何操作。我正在尝试添加点,这已经成功了,然后在事件上删除它们(不成功)。有什么想法吗?

3个回答

41

不要直接在地图上添加所有标记,而是可以将标记添加到一个单独的图层中(即var markers = new L.FeatureGroup();),然后在循环之外将该图层添加到地图上(map.addLayer(markers);)。

例如:

http://jsfiddle.net/9BXL7/

html

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

样式表

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

JavaScript

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()};

如果您需要删除或清除标记层以便在未来使用时更换点,请执行以下操作:

markers.clearLayers();

那看起来就是我要找的。非常感谢。 - Mr. Concolato

12

使用map.removeLayer()

var circle = L.circle([lat, lng], 1000).addTo(map);
map.removeLayer(circle);

仅提供代码的答案通常需要一些解释来配合代码。晚回答可以通过解释它们与现有答案的不同之处而得到改进。 - Jason Aller
2
我不会将其归类为“仅代码”,因为有“使用map.removeLayer:”这些字眼。我认为它与其他内容的区别在于,需要消化的信息更少。我添加这个内容是为了方便那些只是浏览而非详细阅读的人……所以在我有意让某些内容保持简洁的情况下,添加更多信息会显得奇怪。 - f1lt3r

0

你可以直接遍历对象'map'中的所有层。

for ( key in map['_layers'] ){
    if(typeof map['_layers'][key]['feature'] !== 'undefined') {
        var l = map['_layers'][key];
        if( l['feature']['properties']['name'] === 'Company A' ) l.removeFrom(map);}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接