Total distance calculation from LatLng List

Try this please. I tested it with Google Maps and works accurately. You can do a loop and find total distance by using 2 points each time. I added some random dummy data to show how it works. Copy this code to https://dartpad.dartlang.org/ and test easily.

import 'dart:math' show cos, sqrt, asin;

void main() {
  double calculateDistance(lat1, lon1, lat2, lon2){
    var p = 0.017453292519943295;
    var c = cos;
    var a = 0.5 - c((lat2 - lat1) * p)/2 + 
          c(lat1 * p) * c(lat2 * p) * 
          (1 - c((lon2 - lon1) * p))/2;
    return 12742 * asin(sqrt(a));
  }

  List<dynamic> data = [
    {
      "lat": 44.968046,
      "lng": -94.420307
    },{
      "lat": 44.33328,
      "lng": -89.132008
    },{
      "lat": 33.755787,
      "lng": -116.359998
    },{
      "lat": 33.844843,
      "lng": -116.54911
    },{
      "lat": 44.92057,
      "lng": -93.44786
    },{
      "lat": 44.240309,
      "lng": -91.493619
    },{
      "lat": 44.968041,
      "lng": -94.419696
    },{
      "lat": 44.333304,
      "lng": -89.132027
    },{
      "lat": 33.755783,
      "lng": -116.360066
    },{
      "lat": 33.844847,
      "lng": -116.549069
    },
  ];
  double totalDistance = 0;
  for(var i = 0; i < data.length-1; i++){
    totalDistance += calculateDistance(data[i]["lat"], data[i]["lng"], data[i+1]["lat"], data[i+1]["lng"]);
  }
  print(totalDistance);
}

Use the library latlong for common latitude and longitude calculation. This supports both, the "Haversine" and the "Vincenty" algorithm.

List<dynamic> data = [
    {
        "lat": 44.968046,
        "lng": -94.420307
    },
    ...
];


final Distance distance = Distance();
double totalDistanceInM = 0;
double totalDistanceInKm = 0;

for(var i = 0; i < data.length - 1; i++){
    totalDistanceInM += distance(
        LatLng(data[i]["lat"], data[i]["lng"]),
        LatLng(data[i+1]["lat"], data[i+1]["lng"])
    );

    totalDistanceInKm += distance.as(
        LengthUnit.Kilometer, 
        LatLng(data[i]["lat"], data[i]["lng"]), 
        LatLng(data[i+1]["lat"], data[i+1]["lng"]),
    );
}

Update:

Use instead latlong2 that introduce null safety as @Mehul Pamale said in the comments.

Tags:

Gps

Dart

Flutter