大家好(或者我应该说“任何人[谁会读这个...]?):)
我已经尝试了两天找到答案但没有成功(很可能是因为我是一个全新的用户)。我在 Layergroup 中组织了传单 map 标记,因此我可以使用 Layercontrol 管理它们。我希望当一个标记被点击时它会触发一个事件(在我的例子中是创建一个代表这个标记周围特定距离的圆圈)。我想在单个标记之外进行管理,因为我还想根据用户选择的距离为圆的半径设置一些不同的选项。
下面是显示我的意思的不同代码片段:
<!DOCTYPE html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://unpkg.com/leaflet@1.0.2/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.2/dist/leaflet.css"/>
<style>
body {
font-family: Helvetica;
margin:0;
}
#map{
position:absolute;
top:0;
bottom:0;
width:100%;}
</style>
</head>
<body>
<div id="map"></div>
<script>
var sites = [
{'loc':[42.2793869135936,9.53257201027757],'title':'TORRA A I CASELLI'},
{'loc':[42.2713622720985,9.50678498185463],'title':'TOUR GIANDINELLI'},
{'loc':[42.641518105666,9.00587322013212],'title':'TOUR DE LOSARI'},];
var map = new L.Map('map');
map.addLayer(new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'));
map.setView([42.5,9.2210706018535],9);
var marks = new L.LayerGroup();
for(i in sites) {
var title = sites[i].title,
loc = sites[i].loc,
markersites = new L.Marker(new L.latLng(loc), {title: title});
markersites.bindPopup('<strong>'+title+'</strong><br>');
marks.addLayer(markersites);
}
marks.addTo(map);
// for now it is all good, the next part is where I fail
marks.on('click',function(){
console.log("Yeah!");
new L.circle(this.getLatLng(), 10000, {color:'red', fillOpacity:0.3}).addTo(map)});
</script>
</body>
</html>
如有任何帮助,我们将不胜感激,感谢您的关注。
干杯, 纪尧姆。
最佳答案
您使用 LayerGroup 的事实不是您问题的一部分。
首先,您必须在所有标记上附加一个“点击”监听器。这样,您可以在弹出窗口打开时绘制圆圈。您还必须在 javascript 弹出对象中保留对此圈的引用。
// keep a reference on the current active circle
var activeCircle = false;
markersites.on('click', function(e) {
// marker clicked is e.target
// remove active circle if any
if(activeCircle) {
map.removeLayer(activeCircle);
}
// draw a 10km circle with the same center as the marker
activeCircle = L.circle(e.target.getLatLng(), { radius: 10000 , color: "#ff0000" }).addTo(map);
});
关于javascript - 在 leaflet LayerGroup 中的单个标记上触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109053/