buildNearestNeighborRoute static method

List<RoutePoint> buildNearestNeighborRoute(
  1. List<RoutePoint> points,
  2. LatLng startLocation
)

Orders points by proximity starting from startLocation using the nearest neighbor greedy algorithm.

Returns an empty list if points is empty.

Implementation

static List<RoutePoint> buildNearestNeighborRoute(
  List<RoutePoint> points,
  LatLng startLocation,
) {
  if (points.isEmpty) return [];

  final remaining = List<RoutePoint>.from(points);
  final route = <RoutePoint>[];
  var current = startLocation;

  while (remaining.isNotEmpty) {
    remaining.sort((a, b) => haversineDistance(current, a.location)
        .compareTo(haversineDistance(current, b.location)));
    final nearest = remaining.removeAt(0);
    route.add(nearest);
    current = nearest.location;
  }
  return route;
}