Leaflet Routing Machine – How to Export Route Details and Coordinates in JSON / GeoJSON

geojsonjsonleafletrouting

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 …. )

enter image description here

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 a routeselected event. This will return a RouteSelectedEvent with an IRoute 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 of IInstruction objects). Each IInstruction has all the direction types, roads, etc., which can be formatted into human-readable strings using L.Routing.Formatter, as well as the index value of the corresponding point in the coordinates 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:

control.on('routeselected', function(e) {
  var coord = e.route.coordinates;
  var instr = e.route.instructions;
  L.geoJson(getInstrGeoJson(instr,coord)).addTo(map);
});

where getInstrGeoJson is a function that formats the instructions and coordinates into a GeoJSON object:

function getInstrGeoJson(instr,coord) {
  var formatter = new L.Routing.Formatter();
  var instrPts = {
    type: "FeatureCollection",
    features: []
  };
  for (var i = 0; i < instr.length; ++i) {
    var g = {
      "type": "Point",
      "coordinates": [coord[instr[i].index].lng, coord[instr[i].index].lat]
    };
    var p = {
      "instruction": formatter.formatInstruction(instr[i])
    };
    instrPts.features.push({
      "geometry": g,
      "type": "Feature",
      "properties": p
    });
  }
  return instrPts
}

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.