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

标签 javascript mapbox

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

相关文章:

javascript - 抓取 Android 商店

javascript - ID 更改后,JQuery 函数无法在元素上运行

javascript - 关于理解正则表达式的几个问题

ios - 使 Mapbox RMAnnotation 以编程方式显示其标注

ios - 在 MapView 中使用三个 "columns"实现 UITableView [Swift]

ios - 如何在 iOS 应用程序的 Mapbox 中将 GeoJSON 字典显示为热图

javascript - 使用 node-telegram-bot-api 顺序执行功能

javascript - 用于 Backbone.js 的 Visual Studio Intellisense

react-native - 自定义事件以检查样式图像是否在 react native mapbox gl maps 中丢失

ios - 在 MapBox Android 和 iOS 上显示 GeoJSON