【问题标题】:Dynamically add data, remove markers outside of bounds, add markers inside of bounds动态添加数据,删除边界外的标记,在边界内添加标记
【发布时间】:2019-10-09 11:13:41
【问题描述】:

我已经为这个功能苦苦挣扎了好几个星期,但我开始认为这是不可能的。希望这里有人可以证明我错了! :)

使用 Mapbox GL。在页面加载时,地图会在给定范围内使用标记呈现。我试图模仿用户拖动地图的功能,并根据新边界绘制新标记并删除旧标记。新标记的数据是基于 API 请求的动态数据。经过大量谷歌搜索后,我设法找到了一个函数来测试一个点是否在地图的范围内并且有效,但考虑到该函数如何添加/删除标记,动态数据似乎不适合。

我创建了一个小提琴here 并硬编码了一个新的“功能”,但它没有被绘制出来。这个问题很可能还有第二部分,但一旦认为可行,也许我可以自己解决

任何建议将不胜感激。提前致谢!

geojson.features.forEach(function (marker) {
    // create a DOM element for the marker
    var el = document.createElement('div');
    el.className = 'marker';
    el.style.backgroundImage = 'url(https://placekitten.com/g/' + marker.properties.iconSize.join('/') + '/)';
    el.style.width = marker.properties.iconSize[0] + 'px';
    el.style.height = marker.properties.iconSize[1] + 'px';

    el.addEventListener('click', function () {
        window.alert(marker.properties.message);
    });

    // add marker to map
    var point = new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates);

    map.on("dragend", function() {
      if ( inBounds(marker.geometry.coordinates, map.getBounds()) == false ) {
        point.remove();
      } else {
        geojson.features.push({
            "type": "Feature",
            "properties": {
                "message": "Lurman",
                "iconSize": [20, 20]
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -59.29223632812499,
                    -17.28151823530889
                ]
            }
        })
        point.addTo(map); 
      }
    })
});
function inBounds(point, bounds) {
  var lng = (point[0] - bounds._ne.lng) * (point[0] - bounds._sw.lng) < 0;
  var lat = (point[1] - bounds._ne.lat) * (point[1] - bounds._sw.lat) < 0;
  return lng && lat;
}

【问题讨论】:

    标签: mapbox-gl-js


    【解决方案1】:

    我能够通过使用图层并在 dragend 上更新它来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2014-07-13
      • 2022-07-16
      • 2011-07-26
      • 2019-06-16
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      相关资源
      最近更新 更多