Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox Icons/Markers "BearingSnap" or Snap to Position

Is there a way to move icons/markers to a certain location where it will then "snap" to the location?

For example, chess games on the computer where when you move a chess piece to the correct square, it will snap to that position when you let go of the piece near/around the square.

So what I want is to move a marker or an icon to a certain location, let's say the capital of California, and the marker will "snap" to the location that I want when I move it and let go of the marker near the location. But I also want to still be able to move the marker if I want to.

I know Mapbox gl has bearingSnap which snaps the map back to north after the user rotates the map but I can't find anything for just icons/markers and I don't believe I can use bearingSnap for it.

Thanks.

like image 658
user3128376 Avatar asked Dec 05 '25 21:12

user3128376


1 Answers

You can use Turfs distance function: turf.distance(pt1, pt2) to measure distances between 2 points. If then the calculated distance is under a certain threshold, you can set the location of your dragging point to the location of your snap point.

I have you a working example in a 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);
    }
  });
}
like image 88
Andi-lo Avatar answered Dec 11 '25 12:12

Andi-lo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!