我正在使用 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/