如何计算dart中两个位置之间的距离?
不使用插件
double calculateDistance(lat1, lon1, lat2, lon2){
var p = 0.017453292519943295; //conversion factor from radians to decimal degrees, exactly math.pi/180
var c = cos;
var a = 0.5 - c((lat2 - lat1) * p)/2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((lon2 - lon1) * p))/2;
var radiusOfEarth = 6371;
return radiusOfEarth * 2 * asin(sqrt(a));
}
结果是KM。如果您想要米,只需乘以1000。
return 1000 * radiusOfEarth * 2 * asin(sqrt(a))
您可以使用地理定位器插件来计算两个坐标之间的距离:
示例:
var _distanceInMeters = await Geolocator().distanceBetween(
_latitudeForCalculation,
_longitudeForCalculation,
_currentPosition.latitude,
_currentPosition.longitude,
);
查看 GeoLocator 插件 了解更多信息。
查看经纬度。它是一个专门用于处理坐标并具有复杂计算功能的软件包。
与geolocator等软件包不同,它不附带集成的位置服务,可以与专门用于该服务的软件包一起使用。
如果您只需要检查两个坐标之间的距离,您应该使用 Geolocator().distanceBetween,这很简单,但是如果您有一个坐标列表,也许您不希望对每个项目都使用请求,在这种情况下您可以使用此代码来优化性能:
double calculateDistance(LatLng start, LatLng end) {
const double earthRadius = 6371.0; // Radius of the Earth in kilometers
// Convert coordinates to radians
final double lat1 = start.latitude * (pi / 180.0);
final double lon1 = start.longitude * (pi / 180.0);
final double lat2 = end.latitude * (pi / 180.0);
final double lon2 = end.longitude * (pi / 180.0);
// Calculate the differences between the coordinates
final double dLat = lat2 - lat1;
final double dLon = lon2 - lon1;
// Apply the Haversine formula
final double a = sin(dLat / 2) * sin(dLat / 2) +
cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2);
final double c = 2 * atan2(sqrt(a), sqrt(1 - a));
final double distance = earthRadius * c;
return distance; // Distance in kilometers, add "*1000" to get meters
}