Im using dart/flutter and the \'package:latlong/latlong.dart\'
to parse a GPX file into a list of LatLng objects. That is working fine, but the next step is to
This function calculates the distance between two points (given the latitude/longitude of those points).
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'));
}
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"]),
);
}
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 where in 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);
}
I used westdabestdb
's answer. It's okay.
And also, you can use geolocator
plugin for that.
Geolocator.distanceBetween(lat1, lon1, lat2, lon2);
geolocator doc