Mapbox Icons/Markers "BearingSnap" 或捕捉到位置

Mapbox Icons/Markers "BearingSnap" or Snap to Position

有没有办法将 icons/markers 移动到某个位置,然后 "snap" 到该位置?

例如,在计算机上的国际象棋游戏中,当您将棋子移动到正确的格子时,当您松开棋子时它会回到该位置 near/around 格子。

所以我想要的是将标记或图标移动到某个位置,比方说加利福尼亚州的首府,当我移动它并让标记将 "snap" 到我想要的位置时离开该位置附近的标记。但我也希望如果我愿意,仍然可以移动标记。

我知道 Mapbox gl 有 bearingSnap 可以在用户旋转地图后将地图拍回北方,但我找不到任何东西 icons/markers 我不相信我可以使用bearingSnap

谢谢。

这是您可以而且应该在 GL JS 上游实现的功能。当您构造标记或 GeoJSON 特征的坐标时,将其捕捉到所需的网格。

您可以使用Turfs 距离函数:turf.distance(pt1, pt2) 来测量两点之间的距离。如果计算出的距离在某个阈值以下,您可以将拖动点的位置设置为捕捉点的位置。

我在 jsfiddle 中为您提供了一个工作示例: https://jsfiddle.net/andi_lo/nmc4kprn/

function onMove(e) {
  if (!isDragging) return;
  var coords = e.lngLat;

  // Set a UI indicator for dragging.
  canvas.style.cursor = 'grabbing';

  // Update the Point feature in `geojson` coordinates
  // and call setData to the source layer `point` on it.
  geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
  map.getSource('point').setData(geojson);
  
  let snapTo = map.getSource('snap')._data;
  
  turf.featureEach(snapTo, (feature) => {
    let dist = turf.distance(feature, turf.point([coords.lng, coords.lat]));
    console.log(dist);
    // if the distance of the dragging point is under a certain threshold
    if (dist < 500) {
     // set the location of the dragging point to the location of the snapping point
     geojson.features[0].geometry.coordinates = feature.geometry.coordinates;
  map.getSource('point').setData(geojson);
    }
  });
}