位置.onLocationChanged正在调用,即使我不移动



下面的代码显示,在一个颤振小部件中,我使用了location.onLocationChanged监听器,这样我就可以在一个人移动时记录一些点,然后在地图上显示它们作为路径。但它不工作,一旦我来到同一页,它开始连续调用。即使我不动。

@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.red,
containerColor: Colors.white,
borderRadius: 5.0,
loading: false,
text: 'Updating...',
);
setState(() {
isEnding = false;
});
checkLocation();
getCurrentRide();
location.changeSettings(accuracy: LocationAccuracy.high);
locationSubscription =
location.onLocationChanged.listen((LocationData currentLocation) {
// Use current location
if (currentRideId != null && !isEnding) {
final collRef = Firestore.instance.collection('rideLocations');
DocumentReference docReference = collRef.document();
docReference.setData({
"lat": currentLocation.latitude,
"long": currentLocation.longitude,
"time": new DateTime.now(),
"locationId": docReference.documentID,
"rideId": currentRideId,
}).then((doc) {
Timer(Duration(milliseconds: 150), () {
print("init location timer");
// Navigator.pop(context, true);
});
}).catchError((error) {
print(error);
});
}
print(
"currentLocation is --------------- ${currentLocation.latitude}${currentLocation.longitude}");
print("ongoing ref $currentRideId");
});
super.initState();
}

您有一些请求选项来获取位置的准确性和频率。

Accuracy,Interval,Distance

但是你只是告诉了库的准确性。间隔和距离作为默认值传递

location.changeSettings(accuracy: LocationAccuracy.high);

在您的场景中,需要将这些参数告知库。举个例子,

location.changeSettings(accuracy: LocationAccuracy.high.
interval: 10000, 
distanceFilter: 5
);

意思是,

如果超过10秒AND*如果手机移动了至少5米,请给出位置。

*,在Android上,interval和distanceFilter是一起解释的。因此,只有10秒或只有5分钟的移动不会触发onLocationChanged方法

首先,即使你没有移动,也可能会有一些漂移,所以位置会发生一点点变化。

其次,尝试distinct:

ocation.onLocationChanged
.distinct()
.listen((LocationData currentLocation) { ... });

您只需放入单行代码我正在使用这个插件→https://pub.dev/packages/location

//interval add secode in milisecond and add distance
location.changeSettings(interval: 5000,distanceFilter: 5);

最新更新