[GIS] OSRM Routing in Openlayers 3

open-source-routing-machineopenlayers

I'd like to implement routing on my map using OSRM and Openlayers 3 but there don't seem to be any examples or tutorials anywhere. Everyone seems to be utilising Leaflet for this as there is a plugin available.

I understand that I would need to add a layer to hold the geometry and then make a request to viaRoute on the routing server but I'm not sure what form this request should take. I know it requires parameters to be passed in the request in this format:

http://router.project-osrm.org/viaroute?loc=52.503033,13.420526&loc=52.516582,13.429290&instructions=true

My javascript is still a little patchy so I'm not sure how to construct the request and response to be passed to my geometry layer.

Can anyone provide an example of this or perhaps give some guidance as to how it can be achieved?

Best Answer

When you get your route response (this is an encoded polyline) add it like so:

// route is ol.geom.LineString
var route = new ol.format.Polyline({
    factor: 1e6
}).readGeometry(polyline, {
    dataProjection: 'EPSG:4326',
    featureProjection: 'EPSG:3857'
});
var feature = new ol.Feature(route);
feature.setStyle(styles.route);
vectorSource.addFeature(feature);

http://jsfiddle.net/jonataswalker/079xha47/