How to Calculate Total Distance From LatLng List In Flutter

How to Calculate Total Distance From LatLng List In Flutter?

When we use flutter and the ‘package:latlong/latlong.dart‘ to parse a GPX file into a list of LatLng objects. So Lets take a dive into learning how to Calculate Total Distance From LatLng List In Flutter.

How to Calculate Total Distance From LatLng List In Flutter?

You can do a loop and find the total distance by using 2 points each time. Here are some added random dummy data to show how it works.

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);
}

This function calculates the distance between two points. You can also try with the below code snippet:

unit = the unit you desire for results              
      where: 'M' is statute miles (default) 
             'K' is kilometers            
             'N' is nautical miles
String distance(
          double lat1, double lon1, double lat2, double lon2, String unit) {
         double theta = lon1 - lon2;
         double dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) +
         cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(theta));
         dist = acos(dist);
         dist = rad2deg(dist);
         dist = dist * 60 * 1.1515;
          if (unit == 'K') {
            dist = dist * 1.609344;
          } else if (unit == 'N') {
            dist = dist * 0.8684;
          }
          return dist.toStringAsFixed(2);
        }

    double deg2rad(double deg) {
      return (deg * pi / 180.0);
    }

    double rad2deg(double rad) {
      return (rad * 180.0 / pi);
    }

    void main() {
      print("Distance : " + distance(32.9697, -96.80322, 29.46786, -98.53506, 'K'));
    }

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"]),
    );
}

You can also geolocator plugin for the same.

Geolocator.distanceBetween(lat1, lon1, lat2, lon2);

I’ve used the vector_math for converting degree to radians and also the geolocator for getting the current user latitude and longitude.

If in case searching from the current location also there is a method wherein you can calculate the distance between two locations directly as Geolocator.distanceBetween startLatitude, startLongitude, endLatitude, endLongitude.

import 'dart:math' show sin, cos, sqrt, atan2;
import 'package:vector_math/vector_math.dart';
import 'package:geolocator/geolocator.dart';

Position _currentPosition;
double earthRadius = 6371000; 

//Using pLat and pLng as dummy location
double pLat = 22.8965265;   double pLng = 76.2545445; 


//Use Geolocator to find the current location(latitude & longitude)
getUserLocation() async {
   _currentPosition = await GeoLocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}

//Calculating the distance between two points without Geolocator plugin
getDistance(){
   var dLat = radians(pLat - _currentPosition.latitude);
   var dLng = radians(pLng - _currentPosition.longitude);
   var a = sin(dLat/2) * sin(dLat/2) + cos(radians(_currentPosition.latitude)) 
           * cos(radians(pLat)) * sin(dLng/2) * sin(dLng/2);
   var c = 2 * atan2(sqrt(a), sqrt(1-a));
   var d = earthRadius * c;
   print(d); //d is the distance in meters
}

//Calculating the distance between two points with Geolocator plugin
getDistance(){
   final double distance = Geolocator.distanceBetween(pLat, pLng, 
           _currentPosition.latitude, _currentPosition.longitude); 
   print(distance);
}

Conclusion:

Thanks for being with us on a flutter journey!!!

Don’t forget to drop your valuable feedback in the comments.

In this article, we have been through how to calculate the total distance from the LatLng list in flutter.

Do let us know if you need any assistance with flutter development.?? We would love to assist you.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on