【发布时间】:2020-04-13 13:29:10
【问题描述】:
有没有办法在 Flutter 中获取两个位置之间的距离?
【问题讨论】:
有没有办法在 Flutter 中获取两个位置之间的距离?
【问题讨论】:
您可以通过 HaverSine 公式找到距离,在 dart 中实现为:
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。
【讨论】:
如果您正在寻找两个位置之间的最短距离,也就是 LatLng,您可以使用 geolocator 插件。
double distanceInMeters =
await Geolocator().distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);
【讨论】:
flutter_background_geolocation 插件。
如果从当前位置搜索也有一种方法可以计算距离在两个位置之间直接作为 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
}
【讨论】: