Created
July 19, 2021 16:24
-
-
Save alexcmgit/0adc27850f3e079879aca91f7aa9460d to your computer and use it in GitHub Desktop.
Function to calculate distance between two lat and lon points.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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