Visualize agent route

Visualize agent waypoints

The agent route contains of waypoints or planned jobs and route legs between waypoints. Here is a code sample of how an agent waypoints can be visualized with MapLibre GL / Mapbox GL library:

routePlans.forEach((agentPlan) => {
  const items = agentPlan.waypoints.map((waypoint, index) =>
    point(waypoint.location, { index: index + 1 })
  );

  // create points source + layer
  map.addSource(`waypoints-of-agent-${agentPlan.agentIndex}`, {
    type: "geojson",
    data: featureCollection(items),
  });

  map.addLayer({
    id: `waypoints-of-agent-${agentPlan.agentIndex}`,
    type: "circle",
    source: `waypoints-of-agent-${agentPlan.agentIndex}`,
    paint: {
      "circle-radius": 10,
      "circle-color": color, // set any color here
      "circle-stroke-width": 1,
      "circle-stroke-color": darker_color, // set a darker color here
    },
  });

  map.addLayer({
    id: `waypoints-text-of-agent-${agentPlan.agentIndex}`,
    type: "symbol",
    source: `waypoints-of-agent-${agentPlan.agentIndex}`,
    layout: {
      "text-field": "{index}",
      "text-allow-overlap": false,
      "text-font": ["Roboto", "Helvetica Neue", "sans-serif"],
      "text-size": 12,
    },
    paint: {
      "text-color": textColor, // set contrast to the color textColor
    },
  });
});

Visualize agent route legs

The Route Planner API utilizes Route Matrix API that operates with time and distance values. The API result includes an order of waypoints but not the actual route geometry. Call Routing API with agent waypoint to construct and visualize actual agent route:

routePlans.forEach((agentPlan, index) => {
  const waypoints = agentPlan.waypoints.map(waypoint => waypoint.location as Position);

  generateRoute(waypoints, travelMode /* 'drive', 'truck', ...*/).then((routeData: FeatureCollection) => {
    const layerId = `agent-route-${index}`;
    agentPlan.routeLayer = layerId;
    map.addSource(layerId, {
      type: 'geojson',
      data: routeData as any
    });

    map.addLayer({
      'id': layerId,
      'type': 'line',
      'source': layerId,
      'layout': {
        'line-cap': "round",
        'line-join': "round"
      },
      'paint': {
        'line-color': color
      }
    });
    
    return layerId;
  })
});

function generateRoute(points: Position[], mode: string) {
  const waypoints = points.map(position => position[1] + ',' + position[0]).join('|');
  let url = `https://api.geoapify.com/v1/routing?waypoints=${waypoints}&mode=${mode}&apiKey=${apiKey}`;

  return fetch(url).then((resp) => resp.json());
})