Skip to content

Instantly share code, notes, and snippets.

@cladjidane
Last active June 10, 2021 06:53
Show Gist options
  • Save cladjidane/04c930e8318114c2b2492af18dfb7945 to your computer and use it in GitHub Desktop.
Save cladjidane/04c930e8318114c2b2492af18dfb7945 to your computer and use it in GitHub Desktop.
Snap point to roads
/**
* Snap point (coords param) to roads
* The roads depend on the style of the map
* @param {Object Mapbox} map
* @param {Object feature.geometry.coordinates} coords
*/
const snapToRoad = (map, coords) => {
// Coordinate to point conversion
let currentPoint = turf.point([coords.lng, coords.lat]);
// Here we're only retrieving the road layers
let layersRoad = [];
map.getStyle().layers.map(function (layer) {
if (
layer.id.indexOf("road") >= 0 &&
layer.id !== "road-label" &&
layer.type === "line"
) {
layersRoad.push(layer);
}
});
// We're picking up the features of our routes
let snapTo = map.queryRenderedFeatures({
layers: layersRoad.map((layer) => {
return layer.id;
}),
});
// We convert the whole thing into FeatureCollection
var collection = turf.featureCollection(snapTo);
// Which we combine to have only one MultiLines feature.
let lines = turf.combine(collection);
// NearestPointOnLine does the job and finds the point of one of the routes closest to the starting point.
return turf.nearestPointOnLine(lines.features[0], currentPoint);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment