javascriptopenlayersopenlayers-3openlayers-6osrm

How To Draw Path Between Two Location Coordinates Using OSRM Routing Machine in OpenLayers?


How To Draw Path Between Two Location Coordinates Using OSRM Routing Machine in OpenLayers ?


Solution

  • That is very similar to how the route is added in this example https://openlayers.org/en/latest/examples/feature-move-animation.html

    For the route in the OSRM example http://project-osrm.org/docs/v5.7.0/api/#route-service the code would be

    const coordinates = [
      [13.38886, 52.517037],
      [13.397634, 52.529407],
      [13.428555, 52.523219],
    ];
    
    fetch(
      'https://router.project-osrm.org/route/v1/driving/' +
        coordinates.join(';') +
        '?overview=full&geometries=polyline6'
    ).then(function (response) {
      response.json().then(function (result) {
        const polyline = result.routes[0].geometry;
    
        const route = new Polyline({
          factor: 1e6,
        }).readGeometry(polyline, {
          dataProjection: 'EPSG:4326',
          featureProjection: map.getView().getProjection(),
        });
        const routeFeature = new Feature({
          type: 'route',
          geometry: route,
        });
    
        const vectorLayer = new VectorLayer({
          source: new VectorSource({
            features: [routeFeature],
          }),
          style: new Style({
            stroke: new Stroke({
              width: 4,
              color: 'red',
            }),
          }),
        });
    
        map.addLayer(vectorLayer);
        map.getView().fit(routeFeature.getGeometry());
      });
    });
    

    Working example https://codesandbox.io/s/osrm-route-xci7vf