Luk*_*uke 7 javascript geolocation reactjs redux-saga
我使用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 } });
}
}
Run Code Online (Sandbox Code Playgroud)
我理解getUserLocation但是当谈到userPositionPromised时我得不到它.特别是这部分:
location => position.on({location}),
error => position.on({error}),
Run Code Online (Sandbox Code Playgroud)
和
return { getLocation: () => new Promise(location => position.on = location) }
Run Code Online (Sandbox Code Playgroud)
我尝试运行上面的代码,这里出现错误
location => position.on({location}),
error => position.on({error}),
Run Code Online (Sandbox Code Playgroud)
对我有用的是创建一个promise定义,该定义在检索位置时进行解析。例如:
const getUserLocation = () => new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
location => resolve(location),
error => reject(error),
)
})
Run Code Online (Sandbox Code Playgroud)
那么您只需像其他任何服务一样,从生成器内部调用它即可。
function* myGenerator() {
const location = yield call(getUserLocation)
{latitude, longitude} = location.coords;
}
Run Code Online (Sandbox Code Playgroud)
请享用
| 归档时间: |
|
| 查看次数: |
782 次 |
| 最近记录: |