Redux Saga navigator.geolocation.getCurrentPosition
Asked Answered
H

1

7

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) }
Hoard answered 9/3, 2018 at 14:12 Comment(0)
H
9

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

Heshum answered 5/5, 2018 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.