【发布时间】:2018-10-01 11:40:36
【问题描述】:
目标
我需要获取用户位置的纬度和经度以显示路线上的当前位置。我使用@mapbox/react-native-mapbox-gl npm 模块通过 React-Native 实现这一目标。我需要以小频率更新acuret位置,这就是我选择setInrval方法的原因。
问题
我使用下面的函数来获取间隔的位置
watchCurrentLocation() {
try {
this.intervalForWatchPosition = setInterval(() => {
console.log("Here for watch location based on Interval");
// first try with without enableHighAccuracy
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("get user location with interval");
const passengerInfo = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
this.updatePassengerCoordinates(passengerInfo);
},
(error) => {
console.log("Error while getting Current Location : ", error);
},
{ timeout: 10000, maximumAge: 0 });
}, 3000);
} catch (err) {
console.log("Error while current location watch : ", err);
}
}
这个代码snip perfectly working with Android devices,但不知何故它是not working with iOS。在 android 中,它完全按预期工作。它每 3 秒提供一次位置信息,我很容易在路线上更新用户。但是 iOS 设备和模拟器什么都没有发生。没有错误,也没有异常。
在 iOS 中它的触发代码但总是返回单个位置信息作为起点数据。我不知道iOS设备有什么问题。
我已经使用了watchPosition,但是它会在路线上长途旅行后返回结果。该用户从一个位置跳到另一个位置,但现在在路线上顺利导航,所以我不想使用它。这就是为什么我使用带有getCurrentPosition 方法的setInterval 方法。这适用于Android。我使用下面的代码作为 watchPosition
this._watchID = navigator.geolocation.watchPosition((position) => {
const coord = [position.coords.longitude, position.coords.latitude];
this.setCurrentLocationToAsync(coord);
const passengerInfo = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
this.updatePassengerCoordinates(passengerInfo);
},{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
distanceFilter: 1
});
我使用以下版本来实现此功能
@mapbox/react-native-mapbox-gl: 6.1.2
react-native: 0.55.4
以前有人遇到过这种问题吗?或者知道如何在 iOS 上解决它?
新更新的代码
我也尝试过使用递归方法来避免使用如下异步调用的 setInterval 方法,但它仍然无法在 iOS 上运行......!!!
watchCurrentLocation() {
getCurrentPositionTimeoutHandle = setTimeout(() => {
// first try with without enableHighAccuracy
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("get user location with setTimeout 1");
const passengerInfo = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
this.updatePassengerCoordinates(passengerInfo);
if (getCurrentPositionTimeoutHandle) {
console.log("Timeout function exist so call that again 2");
this.watchCurrentLocation();
}
},
(error) => {
console.log("Error while getting Current Location : ", error);
//console.log("Error while executing timeout way method 3");
this.watchCurrentLocation()
},
{ timeout: 20000, maximumAge: 0 });
}, 3000);
}
希望能有办法解决。
【问题讨论】:
-
你有解决办法吗?
-
你最后做了什么?我有同样的问题。我通过将时间间隔更改为 15 秒并使用 await 来获取 getCurrentPosition 的结果,但这不是一个好的解决方案。它适用于所有浏览器和 Android,但不适用于 iOS。
标签: ios react-native geolocation setinterval