Estoy tratando de obtener la ubicación de los usuarios usando la API de geolocalización, en mi devolución de llamada exitosa quiero devolver la función getPosition con el valor de posición.
He intentado algunos enfoques, pero ninguno de ellos ha tenido éxito hasta ahora, aquí es donde estoy ahora.
function getPosition() { // If geolocation is available, try to get the visitor's position if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(successCallback, errorCallback); console.log("Getting the position information...") } else { alert("Sorry, your browser does not support HTML5 geolocation."); } function successCallback(position) { return position } function errorCallback(error) { alert("Sorry, we can't retrieve your local weather without location permission."); } }; const getLocalWeather = async () => { if(loading === 'loading') return setLoading('loading') console.log(getPosition()) // this console log should return the position from getPosition setLoading('done') };La función getPosition en sí funciona bien, pero no puedo acceder a su valor de retorno en la función getLocalWeather.
Cualquier ayuda sería apreciada, he estado atascado en esto por un tiempo.
Ya está familiarizado con async/await por lo que parece, así que envuelva su código getPosition en una promesa y luego await la respuesta en getLocalWeather .
Es posible que este código no funcione en el fragmento, pero lo probé localmente y registra la posición sin ningún problema.
function getPosition() { return new Promise((res, rej) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(success, error); } else { console.log("Sorry, your browser does not support HTML5 geolocation."); } function success(position) { res(position) } function error(error) { console.log("Sorry, we can\'t retrieve your local weather without location permission."); } }); }; async function getLocalWeather() { console.log(await getPosition()) }; getLocalWeather();