如何在 OpenLayers 中使用 OSRM 路由机绘制两个位置坐标之间的路径?

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

如何在 OpenLayers 中使用 OSRM 路由机绘制两个位置坐标之间的路径?

这与本例中添加路由的方式非常相似https://openlayers.org/en/latest/examples/feature-move-animation.html

对于 OSRM 示例中的路由 http://project-osrm.org/docs/v5.7.0/api/#route-service,代码将是

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());
  });
});

工作示例https://codesandbox.io/s/osrm-route-xci7vf