我使用redux saga创建应用程序,我遇到地理位置问题.
其实我找到了解决方案,但我不明白它是如何工作的.
function userPositionPromised() {
const position = {}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition (
location => position.on({location}),error => position.on({error}),{ enableHighAccuracy: true }
)
}
return { getLocation: () => new Promise(location => position.on = location) }
}
function* getUserLocation() {
yield put({type: GET_LOCATION_REQUESTED});
const { getLocation } = yield call(userPositionPromised)
const { error,location } = yield call(getLocation)
if (error) {
console.log('Failed to get user position!',error)
const { message,code } = error;
yield put({type: GET_LOCATION_Failed,payload: { code,message }});
} else {
console.log('Received User Location',location)
const { latitude: lat,longitude: lng } = location.coords;
yield put({type: GET_LOCATION_SUCCESS,payload: { lat,lng } });
}
}
我理解getUserLocation但是当谈到userPositionPromised时我得不到它.特别是这部分:
location => position.on({location}),
和
return { getLocation: () => new Promise(location => position.on = location) }
最佳答案
我试过运行上面的代码,我在这里得到了一个错误
原文链接:https://www.f2er.com/js/429254.htmllocation => position.on({location}),
对我有用的是创建一个在检索位置时解决的承诺定义.例如:
const getUserLocation = () => new Promise((resolve,reject) => {
navigator.geolocation.getCurrentPosition(
location => resolve(location),error => reject(error),)
})
function* myGenerator() {
const location = yield call(getUserLocation)
{latitude,longitude} = location.coords;
}
请享用