TomTom Maps for JavaScript
    Preparing search index...

    Function findBestWaypointInsertionIndex

    • Finds the best index to insert a new waypoint into an existing route.

      This function determines the optimal position to insert a new waypoint among existing waypoints by finding where it fits most naturally along the route line. The algorithm:

      1. Projects each existing waypoint onto the route line to find their closest points
      2. Projects the new waypoint onto the route line
      3. Determines where the new waypoint fits based on its position along the route

      Parameters

      • route: Route

        The existing calculated route Feature with LineString geometry

      • existingWaypoints: WaypointLike[]

        Array of existing waypoints in order (origin, intermediate waypoints, destination)

      • newWaypoint: WaypointLike

        The new waypoint to insert

      Returns number

      The index where the new waypoint should be inserted (0 means insert at the beginning, existingWaypoints.length means append at the end)

      • If the route has no coordinates, returns 0
      • If there are fewer than 2 existing waypoints, returns 0
      • The function finds where the new waypoint naturally fits along the route's progression
      • This creates a more streamlined route by minimizing detours
      const route: Route = {
      type: 'Feature',
      id: 'route-1',
      geometry: {
      type: 'LineString',
      coordinates: [[4.9, 52.3], [4.95, 52.35], [5.0, 52.4]]
      },
      properties: { ... },
      bbox: [4.9, 52.3, 5.0, 52.4]
      };

      const waypoints: WaypointLike[] = [
      [4.9, 52.3], // origin
      [5.0, 52.4] // destination
      ];

      const newWaypoint: WaypointLike = [4.95, 52.35];

      const insertIndex = findBestWaypointInsertionIndex(route, waypoints, newWaypoint);
      // Returns: 1 (insert between origin and destination)

      const updatedWaypoints = [
      ...waypoints.slice(0, insertIndex),
      newWaypoint,
      ...waypoints.slice(insertIndex)
      ];