获取 mapbox 地图范围内的标记列表

Get list of markers within bounds of mapbox map

我正在尝试获取地图范围内的所有标记。当用户与地图交互时(缩放 in/out、移动、单击),我想获取地图边界内的所有标记以显示这些标记的列表。

我尝试实现这个例子中的一些功能,但没有成功:https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/

这是 codepen 上地图的工作版本:https://codepen.io/anon/pen/MPGgWq

我查看了它返回的特征和边界,none 这些信息帮助我完成了这项工作。我正在使用标记,因此我可以显示自定义标记图像并设置出现在弹出框中的描述。

map.on('moveend', function (e) {
    var features =  map.queryRenderedFeatures();
    var bounds = map.getBounds();

    console.log(features);
    console.log(bounds);
});

据我了解 mapbox gl js API 你 不能 查询标记。我要做的是在某种数据结构中有一个标记列表,并使用 turf.js pointsWithinPolygon 函数进行查询。第一个输入是您的标记,第二个是您当前的视口。

1) Mapbox gl js don't store references for markers - https://github.com/mapbox/mapbox-gl-js/issues/5821#issuecomment-356704579

2) 如果标记被添加到地图中但没有保存,那么它的唯一表示是地图容器中的 html 元素。

3) 所以你可以使用getBoundingClientRect来判断标记在地图容器中是否可见:

function intersectRect(r1, r2) {
  return !(r2.left > r1.right ||
    r2.right < r1.left ||
    r2.top > r1.bottom ||
    r2.bottom < r1.top);
}

function getVisibleMarkers() {
  var cc = map.getContainer();
  var els = cc.getElementsByClassName('marker');
  var ccRect = cc.getBoundingClientRect();
  var visibles = [];
  for (var i = 0; i < els.length; i++) {
    var el = els.item(i);
    var elRect = el.getBoundingClientRect();
    intersectRect(ccRect, elRect) && visibles.push(el);
  }
  if (visibles.length > 0) console.log(visibles);
}

[https://jsfiddle.net/rkqdz5g2/]