我想知道是否有人知道在使用此约定添加点后如何实际删除一层点:
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);
}
典型的removeLayer(pointsLayer);在类似的for循环中对我不起作用。但是,这并不意味着没有办法循环。我只是不确定如何。我正在尝试添加有效的点,然后在事件中删除它们(不工作)。有什么想法吗?
谢谢大家。
P.S。如果您认为这个问题相关或有帮助,请不要忘了竖起大拇指,欢呼。
答案 0 :(得分:39)
您可以在单独的图层上添加标记(例如var markers = new L.FeatureGroup();
),然后在地图(map.addLayer(markers);
)上添加该图层,而不是直接在地图上添加所有标记。< / p>
例如,
<强> 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 © 2011 OpenStreetMap contributors, Imagery © 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();
答案 1 :(得分:11)
使用map.removeLayer()
:
var circle = L.circle([lat, lng], 1000).addTo(map);
map.removeLayer(circle);
答案 2 :(得分:0)
您可以直接在对象&#39; map&#39;。
中浏览所有图层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);}}