I create app with redux saga and I have problem with geolocation. Actually I found the solution but I don't understand how it works.
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 } });
}
}
I understand getUserLocation but when it comes to userPositionPromised I don't get it. Especially this part:
location => position.on({location}),
error => position.on({error}),
and
return { getLocation: () => new Promise(location => position.on = location) }
I tried running the code above, I got an error here
location => position.on({location}),
error => position.on({error}),
What worked for me was to create a promise definition that resolves upon retrieving a location. For example:
const getUserLocation = () => new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
location => resolve(location),
error => reject(error),
)
})
then you simply call this from within the generator like any other service.
function* myGenerator() {
const location = yield call(getUserLocation)
const {latitude, longitude} = location.coords;
}
Enjoy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With