2

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?

0

1 Answer 1

6

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/

12
  • Orsm as ever Jonatas! This is exactly what I was looking for and I suspected that the returned JSON would be pushed onto a feature as geometries but there's no way I would have figured out the Polyline specifics. Thanks so much, I now have a way to build on this and return directions to the user! ;)
    – dvmac01
    Commented Oct 19, 2015 at 15:07
  • @JonatasWalker the fiddle works fine for two points. if I have multiple way points, what should I do ?
    – KcYoosuf
    Commented Apr 30, 2016 at 9:06
  • @KcYoosuf Just add some more logic, see updated fidlle. Commented Apr 30, 2016 at 11:14
  • I have managed to work thins perfectly using the fiddle. In my application all the lat-long values are from database fro showing a specific bus route. My question is, how can I disable displaying of alternate routes in OSRM
    – KcYoosuf
    Commented May 3, 2016 at 4:14
  • @KcYoosuf maybe you create a new question with all the details. Commented May 3, 2016 at 5:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.