Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Created July 19, 2021 16:24
Show Gist options
  • Save alexcmgit/0adc27850f3e079879aca91f7aa9460d to your computer and use it in GitHub Desktop.
Save alexcmgit/0adc27850f3e079879aca91f7aa9460d to your computer and use it in GitHub Desktop.
Function to calculate distance between two lat and lon points.
import 'dart:math' as math;
void main() {
/// Online Tool https://www.meridianoutpost.com/resources/etools/calculators/calculator-latitude-longitude-distance.php?
final distance = DistanceUtils.distanceBetween(40.689202777778, -74.044219444444, 38.889069444444, -77.034502777778);
print(distance);
}
abstract class DistanceUtils {
static String formatDistance(int meters) {
final km = (meters * 0.001).toStringAsFixed(1);
return km;
}
/// Implementation of [this algorithm](https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula)
static double distanceBetween(double lat1, double lon1, double lat2, double lon2) {
final p = math.pi / 180;
final cos = math.cos;
final value = 0.5 -
cos((lat2 - lat1) * p) / 2 +
cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2;
return 12742 * math.asin(math.sqrt(value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment