如何计算Flutter上两个位置之间的距离?(结果应该是米)



如何计算飞镖中两个位置之间的距离?

不使用插件

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));
}

结果是KM。如果您想要,只需乘以1000return 1000 * 12742 * asin(sqrt(a))

您可以使用地理定位器插件来计算两个坐标之间的距离:

示例:

var _distanceInMeters = await Geolocator().distanceBetween(
_latitudeForCalculation,
_longitudeForCalculation,
_currentPosition.latitude,
_currentPosition.longitude,
);

查看GeoLocator插件了解更多信息。

查看latlong。这是一个专门处理坐标的软件包,具有复杂的计算功能。

与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
}

您可以使用latlong2,它是latlong的延续。它具有距离计算和路径绘制等功能。所以你可以得到距离作为路径距离和直接距离。

最新更新