问题描述
我已经开始使用leaflet作为开源地图,http://leaflet.cloudmade.com/
I have started using leaflet as an open source map, http://leaflet.cloudmade.com/
以下 jQuery 代码将启用在地图点击时在地图上创建标记:
The following jQuery code will enable the creation of markers on the map on map click:
map.on('click', onMapClick);
function onMapClick(e) {
var marker = new L.Marker(e.latlng, {draggable:true});
map.addLayer(marker);
marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
};
但我目前(在我的代码中)无法删除现有标记,或者找到我在地图上创建的所有标记并将它们放入数组中.谁能帮我理解如何做到这一点?传单文档可在此处获得:http://leaflet.cloudmade.com/reference.html
But there is currently no way for me (in my code) to delete existing markers, or find all the markers i've created on a map and put them into an array. Can anyone help me understand how to do this? Leaflet documentation is available here : http://leaflet.cloudmade.com/reference.html
推荐答案
你必须把你的var marker"放到函数之外.稍后您可以访问它:
you have to put your "var marker" out of the function. Then later you can access it :
var marker;
function onMapClick(e) {
marker = new L.Marker(e.latlng, {draggable:true});
map.addLayer(marker);
marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
};
然后:
map.removeLayer(marker)
但是这样你只能拥有最新的标记,因为每次,var 标记都会被最新的擦除.所以一种方法是创建一个全局标记数组,然后将标记添加到全局数组中.
But you can only have the latest marker that way, because each time, the var marker is erased by the latest. So one way to go is to create a global array of marker, and you add your marker in the global array.
这篇关于传单 - 如何找到现有的标记,并删除标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!