I need to export / save the route details found using Leaflet Routing Machine in JSON or GeoJSON format.
I've tried to use
var routeArray = new Array();
routeArray = control.getWaypoints();
alert (JSON.stringify(routeArray));
that works but in this manner I obtain only the waypoints and, instead, I'm interested at ALL the route details (coordinates and descriptions).
I guess that "somewhere" they are (in the picture when I put my mouse pointer on a description I can see a little blue circle on the map as you can see …. )
Any suggestion, example, jsfiddle to help me?
Best Answer
You can access the instructions (that is, the turns etc.) by attaching a listener to your
Routing.Control
for arouteselected
event. This will return aRouteSelectedEvent
with anIRoute
object inside it.The IRoute contains the coordinates of the route path and waypoints (as arrays of
L.LatLng
objects) as well as the routing instructions (as an array ofIInstruction
objects). Each IInstruction has all the direction types, roads, etc., which can be formatted into human-readable strings usingL.Routing.Formatter
, as well as theindex
value of the corresponding point in thecoordinates
array.Bringing all this together, here's a fiddle that extracts the instruction points and adds them to the map:
http://fiddle.jshell.net/nathansnider/kLymv7vc/
Here's the event listener code:
where
getInstrGeoJson
is a function that formats the instructions and coordinates into a GeoJSON object:The Leaflet.Routing.Machine author has also written some routines for exporting the routes and waypoints as GeoJSON (discussed here). Combining these with the code above, you could get GeoJSON for all the features that the routing machine produces.