当我将弹出窗口绑定到单个标记时,它可以正常工作:
const ugh = L.marker([60.6157376, 10.27716])
.addTo(this.leafleftMap)
.bindPopup("I work")
当我从API调用向地图添加标记时,它也可以正常工作:
const markers = new L.FeatureGroup()
displayedStories.forEach((marker, i) => {
let m = L.marker(marker.coords)
markers.addLayer(m)
})
但是当我查看列表时,我无法将弹出窗口绑定到每个标记:
const markers = new L.FeatureGroup()
displayedStories.forEach((marker, i) => {
const m = L.marker(marker.coords)
.addTo(this.leafleftMap)
.bindPopup("I don't work")
markers.addLayer(m)
})
我也尝试过LayerGroups,按照我在the docs中找到的一个例子:
const markers = displayedStories.map(story => L.marker(story.coords)
.bindPopup("I don't work"))
const storyMarkers = L.layerGroup(markers)
在上面的两个示例中,标记仍然显示在地图上,但是当我点击它们时没有弹出窗口。
我的猜测是它与将m
常量重新分配给列表中的每个项目有关,尽管我可能错了。
答案 0 :(得分:1)
你的两个例子应该没有问题:
var map = L.map('map');
var displayedStories = [{
coords: [60.6157376, 10.27716]
}, {
coords: [61.6157376, 10.27716]
}, {
coords: [62.6157376, 10.27716]
}];
var displayedStories2 = [{
coords: [60.6157376, 11.27716]
}, {
coords: [61.6157376, 11.27716]
}, {
coords: [62.6157376, 11.27716]
}];
const markers = new L.FeatureGroup().addTo(map);
displayedStories.forEach((marker, i) => {
const m = L.marker(marker.coords)
.addTo(map)
.bindPopup("I don't work")
markers.addLayer(m)
});
const markers2 = displayedStories2.map(story => L.marker(story.coords)
.bindPopup("I don't work2"))
const storyMarkers = L.layerGroup(markers2).addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.fitBounds(markers.getBounds().pad(.2));
&#13;
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>
<div id="map" style="height: 200px"></div>
&#13;