Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Saga navigator.geolocation.getCurrentPosition

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) }
like image 461
Luke Avatar asked Mar 09 '18 14:03

Luke


1 Answers

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

like image 97
alaboudi Avatar answered Sep 20 '22 04:09

alaboudi