Skip to content

Instantly share code, notes, and snippets.

@Maverick-I0
Last active April 25, 2021 09:02
Show Gist options
  • Select an option

  • Save Maverick-I0/ec3efa7c1be22d71cbd7ea91dfd66a3f to your computer and use it in GitHub Desktop.

Select an option

Save Maverick-I0/ec3efa7c1be22d71cbd7ea91dfd66a3f to your computer and use it in GitHub Desktop.
Shortest distance Between Geo-Coordinates In Dart using Haversine formula
import 'dart:math' show pi, pow;
void main() {
final double lat1=50.06638889;
final double lat2=58.64388889;
final double lng1=5.71472222;
final double lng2=3.06777778;
/// Calculates the minimum distance between ([lat1],[lng1]) and ([lat2],[lng2]).
/// The function returns the distance in meters.
/// [lat1], [lng1], [lat2] and [lng2] !=null.
double calculateDistance (double lat1,double lng1,double lat2,double lng2){
const double radEarth =6.3781*( pow(10.0,6.0)); // in meters
double phi1= lat1*(pi/180);
double phi2 = lat2*(pi/180);
double delta1=(lat2-lat1)*(pi/180);
double delta2=(lng2-lng1)*(pi/180);
double cal1 = sin(delta1/2)*sin(delta1/2)+(cos(phi1)*cos(phi2)*sin(delta2/2)*sin(delta2/2));
double cal2= 2 * atan2((sqrt(cal1)), (sqrt(1-cal1)));
double distance =radEarth*cal2;
return (distance);
}
double a=calculateDistance(lat1,lng1,lat2,lng2);
print(a);
}
@Maverick-I0
Copy link
Author

  • This program returns the distance in meters.
  • To get the distance of a path consisting of multiple coordinates, run the calculateDistance function inside a for loop and keep appending the result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment