Get route steps

By default, the resulting Map Matching Feature geometry contains the whole route. However, sometimes it's required to split the route info the steps and points between them. Here is an example of how this can be done.

We used Turf library to operate with GeoJSON objects. You can install the library by running npm install @turf/helpers.

import {
  FeatureCollection,
  multiPoint,
  lineString,
  point,
  featureCollection,
  Feature,
  LineString,
  Point,
  MultiLineString,
} from "@turf/helpers";

// mapMatchingData => the FeatureCollection object returned by Map Matching API
function splitMapMatchingResultIntoSteps(mapMatchingData: FeatureCollection) {
  const legSteps: Feature<LineString, any>[] = [];
  const pointsBetweenSteps: Feature<Point, any>[] = [];

  if (!mapMatchingData.features?.length) {
    return null;
  }

  mapMatchingData.features[0].properties.legs.forEach((leg, index) => {
    const points: number[][] = (mapMatchingData.features[0]
      .geometry as MultiLineString).coordinates[index];

    leg.steps.forEach((step, index) => {
      const stepCoords: number[][] = points.slice(
        step.from_index,
        step.to_index + 1
      );
      legSteps.push(lineString(stepCoords, step));

      if (index > 0) {
        pointsBetweenSteps.push(point(points[step.from_index]));
      }
    });
  });

  return {
    steps: legSteps,
    points: pointsBetweenSteps
  }
}