gpt4 book ai didi

javascript - Mapbox 只添加最后一个标记?

转载 作者:行者123 更新时间:2023-11-30 14:37:46 25 4
gpt4 key购买 nike

我正在使用 mapbox 并在 map 上放置多个标记。我的代码看起来像这样:

add.locations.forEach((location) => {
console.log(location.long + " " + location.lat);
// add marker to map
let marker = new mapboxgl.Marker(el)
.setLngLat([location.long, location.lat])
.setPopup(popup)
.addTo(this.map);

this.markers.push(marker);
});

当我查看控制台时,console.log(location.long + ""+ location.lat); 显示了 2 个不同的经度和纬度。但是在 map 上只有最后一个位置/指针在那里!?

这里可能出了什么问题?

最佳答案

看起来您正在为所有标记使用相同的 el 容器,因此在每次循环之后,新标记将覆盖前一个(因此只保留最后一个)。

您应该为每个标记创建一个容器:

add.locations.forEach((location) => {

// create a HTML element for each feature
const el = document.createElement('div');

// make a marker for each feature and add to the map
const marker = new mapboxgl.Marker(el)
.setLngLat([location.long, location.lat])
.setPopup(popup)
.addTo(this.map);

this.markers.push(marker);
});

https://www.mapbox.com/help/custom-markers-gl-js/#add-markers-to-the-map

关于javascript - Mapbox 只添加最后一个标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50154412/

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