Mapbox snap to position

Mapbox Icons Markers snap to position

HTML

<script src="	https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css">
<div id="map"></div>
<pre id='coordinates' class='coordinates'></pre>

CSS

#map {
  height: 500px;
}

JavaScript

mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';

var isDragging;

// Is the cursor over a point? if this
// flag is active, we listen for a mousedown event.
var isCursorOverPoint;

var coordinates = document.getElementById('coordinates');

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v9',
  center: [0, 0],
  zoom: 2
});


var canvas = map.getCanvasContainer();

var geojson = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "Point",
      "coordinates": [34, 76]
    }
  }]
};

function mouseDown() {
  if (!isCursorOverPoint) return;

  isDragging = true;

  // Set a cursor indicator
  canvas.style.cursor = 'grab';

  // Mouse events
  map.on('mousemove', onMove);
  map.once('mouseup', onUp);
}

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);
    }
  });
}

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

  // Print the coordinates of where the point had
  // finished being dragged to on the map.
  coordinates.style.display = 'block';
  coordinates.innerHTML = 'Longitude:...