Search code examples
javascriptleafletosrmmap-matchingleaflet-routing-machine

How to use OSRM match api in leaflet to draw a route?


I have some gps generated data during a drive.

var routeArr = [{lng1, lat1}, {lng2,lat2}, {lng3, lat3}.....];

I want to show this generated data as actual route traveled on a Leaflet powered Openstreet map. My naive approach is to show a polyline connecting all points. But I want to show actual route which was followed while driving. Can I use OSRM-Backend API with leaflet-routing-machine plugin for this? Any help will be much appreciated.


Solution

  • Sadly there is not drop-in way to use this with LRM since the APIs work slightly differently.

    1. The response contains tracepoints and matchings instead of waypoints and routes
    2. An object in the matchings array is similar to a Route object but it represent sections of the gps trace that could be matched, not alternative routes like in the route plugin.

    Easiest way to just deploy this on a map would be to run a query against:

    http://router.project-osrm.org/match/v1/driving/{lon,lat};{lon,lat};...?overview=full

    And then use https://github.com/mapbox/polyline and the following snippet to add the geometry on a map:

    var polyline = require('polyline');
    
    /* fetch the URL and save JSON in response */
    
    response.matchings.map((m) => L.polyline(polyline.decode(m.geometry)).addTo(map));