gpt4 book ai didi

javascript - 将弹出窗口绑定(bind)到 Leaflet.js 中的动态标记列表

转载 作者:行者123 更新时间:2023-11-30 20:47:18 25 4
gpt4 key购买 nike

当我将弹出窗口绑定(bind)到单个标记时,它工作正常:

const ugh = L.marker([60.6157376, 10.27716])
.addTo(this.leafleftMap)
.bindPopup("I work")

当我通过 API 调用向 map 添加标记时,它也能正常工作:

const markers = new L.FeatureGroup()
displayedStories.forEach((marker, i) => {
let m = L.marker(marker.coords)
markers.addLayer(m)
})

但我无法在遍历列表时将弹出窗口绑定(bind)到每个标记:

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)

在上面的两个例子中,标记仍然出现在 map 上,但是当我点击它们时没有弹出窗口打开。

我的猜测是,它与将 m 常量重新分配给列表中的每个项目有关,尽管我可能错了。

最佳答案

你的两个例子应该没​​有问题:

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: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

map.fitBounds(markers.getBounds().pad(.2));
<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>

关于javascript - 将弹出窗口绑定(bind)到 Leaflet.js 中的动态标记列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48570982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com