Leafletjs:如何访问和更新图层内的标记
Leafletjs: how to access and update a marker inside a layer
我有一个包含不同位置的列表。每次有人点击一个位置时,我都会从我的地图中删除标记层,然后触发一个功能,使新的标记层与以前的位置相同,只是这次对所选位置使用不同的图标。
我的问题是我不想删除和添加图层,而是只想更新特定标记的图标,但找不到访问它的方法。
有人提到这可以通过 .eachLayer 函数实现,但我看不出如何实现,因为这是控制层,而不是标记。
markers = new L.featureGroup();
function updateMarker(locations, clickedID){
//Adding all markers on map
for (var i = 0; i < locations.length; i++)
{
//red marker for the selected location
if (locations[i][2] == clickedID){
marker = new L.marker([locations[i][0],locations[i][1]],{
icon: redIcon})
.bindPopup(locations[i][3]);
markers.addLayer(marker);
}
else{
//add regular marker
marker = new L.marker([locations[i][0],locations[i][1]])
.bindPopup(locations[i][3])
.addTo(map);
markers.addLayer(marker);
}
} ;
map.addLayer(markers);
}
没有例子,你想达到的效果不是100%清楚。
但是,如果您想操作标记(例如使用 setIcon()),则保留所有标记的数组会容易得多。
var markers = {}; // list of created markers
创建标记时,将其添加到数组中
markers[theID] = L.marker();
map.addLayer(markers[theID]);
然后您可以轻松修改您的标记,而无需扫描您的特征组。
markers[theID].setIcon();
我有一个包含不同位置的列表。每次有人点击一个位置时,我都会从我的地图中删除标记层,然后触发一个功能,使新的标记层与以前的位置相同,只是这次对所选位置使用不同的图标。
我的问题是我不想删除和添加图层,而是只想更新特定标记的图标,但找不到访问它的方法。
有人提到这可以通过 .eachLayer 函数实现,但我看不出如何实现,因为这是控制层,而不是标记。
markers = new L.featureGroup();
function updateMarker(locations, clickedID){
//Adding all markers on map
for (var i = 0; i < locations.length; i++)
{
//red marker for the selected location
if (locations[i][2] == clickedID){
marker = new L.marker([locations[i][0],locations[i][1]],{
icon: redIcon})
.bindPopup(locations[i][3]);
markers.addLayer(marker);
}
else{
//add regular marker
marker = new L.marker([locations[i][0],locations[i][1]])
.bindPopup(locations[i][3])
.addTo(map);
markers.addLayer(marker);
}
} ;
map.addLayer(markers);
}
没有例子,你想达到的效果不是100%清楚。
但是,如果您想操作标记(例如使用 setIcon()),则保留所有标记的数组会容易得多。
var markers = {}; // list of created markers
创建标记时,将其添加到数组中
markers[theID] = L.marker();
map.addLayer(markers[theID]);
然后您可以轻松修改您的标记,而无需扫描您的特征组。
markers[theID].setIcon();