现有的标记(工作)已使用类似经度和纬度的N块分配给地图:
m = [42.0167, 24.8667];
marker = L.marker([m[0], m[1]]);
markers.addLayer(marker);
m
,marker
和markers
是全局变量。
现在,我希望清除地图上的现有标记,并在replaceWithNewMarkers(data)
执行后立即放置新的ajax数据数组:
function replaceWithNewMarkers(data) {
var obj = jQuery.parseJSON( data );
//markers.clearLayers(); // #this clears all the markers
//markers = L.markerClusterGroup();
// THE FOLLOWING IS ABLE TO ADD NEW MARKERS TO EXISTING MAP
$.each(obj, function(myVal) {
m = [obj[myVal][0], obj[myVal][1]];
marker = L.marker([m[0], m[1]]);
markers.addLayer(marker);
});
}
这适用于添加新标记,但我无法移除现有标记。我尝试添加markers.clearLayers();
来清除标记,但这样做会完全隐藏标记(无法显示新的标记集)。
有关如何实现这一目标的任何建议吗?
-------添加细节-------
以下是当前正在加载默认标记的初始化程序。
<script>
var m;
var marker;
var markers;
var map;
var tiles;
var latlng;
var baseLayer;
window.onload = function() {
tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors, Points © 2012 LINZ'
});
latlng = L.latLng(25, -80);
map = new L.Map('map-canvas', {
center: latlng,
zoom: 2,
minZoom: 2,
maxBounds: L.latLngBounds(L.latLng(85,-120), L.latLng(-85, 120)),
layers: [tiles]
});
markers = L.markerClusterGroup();
m = [40.27, 25.87];
marker = L.marker([m[0], m[1]]);
markers.addLayer(marker);
m = [37.455, 20.94];
marker = L.marker([m[0], m[1]]);
markers.addLayer(marker);
m = [57.25, 61.0];
marker = L.marker([m[0], m[1]]);
markers.addLayer(marker);
map.addLayer(markers);
};
baseLayer = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
maxZoom: 18
}
);
</script>
答案 0 :(得分:1)
使用&#34; map.removeLayer(markers)&#34;删除图层
function resetMarkers() {
if (map.hasLayer(markers)) {
map.removeLayer(markers);
markers= new L.markerClusterGroup();
map.addLayer(markers);
}
}
function replaceWithNewMarkers(data) {
var obj = jQuery.parseJSON( data );
resetMarkers();
// THE FOLLOWING IS ABLE TO ADD NEW MARKERS TO EXISTING MAP
$.each(obj, function(myVal) {
m = [obj[myVal][0], obj[myVal][1]];
marker = L.marker([m[0], m[1]]);
markers.addLayer(marker);
});
}
//编辑:将标记层重命名为标记 //编辑2:newMarkerClusterGroup =&gt; L.markerClusterGroup();