Making polyline snap to roads in leaflet
This can be done rather easily with leaflet-routing-machine. You can just set the waypoints
to your latlngArray
when you initialize the routing control:
var control = L.Routing.control({
waypoints: latlngArray,
show: false,
waypointMode: 'snap',
createMarker: function() {}
}).addTo(map);
Here, show: false
keeps the control from displaying on the map, and the empty createMarker
function overrides the default markers that routing machine creates, instead doing nothing (though the markers would be removed when we remove the control, this just keeps them from flashing on the screen when a route is found).
You can extract all the vertices of the routing machine results by listening for the routeselected
event, which will return an IRoute
object that contains all the directions and geometries for the route. Placing the .route.coordinates
in a new L.polyline
object will keep the route around, so we can then just get rid of the routing control:
control.on('routeselected', function(e) {
L.polyline(e.route.coordinates).addTo(group);
map.removeControl(control);
});
Placing the above code blocks within your .success
callback function right after you populates your latlngArray
should give you the route you want. Here's a fiddle showing this at work:
http://fiddle.jshell.net/nathansnider/ygktexbj/
Also, if you're not using the routing control for anything else and want to keep it from showing up entirely (a small white control box may still appear while the route is being calculated), you can simply hide it in CSS:
.leaflet-routing-container {
display:none;
}