有什么方法可以获取Flutter中两个位置之间的距离吗?
答案 0 :(得分:0)
如果您正在寻找两个位置(即LatLng)之间最短的距离,可以使用geolocator插件。
double distanceInMeters =
await Geolocator().distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);
答案 1 :(得分:0)
您可以通过在镖中实现的HaverSine公式找到距离:
import'dart:math' as Math;
void main()=>print(getDistanceFromLatLonInKm(73.4545,73.4545,83.5454,83.5454));
double getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
double deg2rad(deg) {
return deg * (Math.pi/180);
}
输出:
1139.9231530436646
Source in Javscript并归功于Chuck。
答案 2 :(得分:0)
如果在当前位置搜索的情况下,我还使用vector_math
将度数转换为弧度,还使用geolocator
获得当前用户的纬度和经度可以直接通过 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); //distance in meters
}