getCurrentPosition PWA Реагирует не может вернуть позицию сбой

#reactjs #typescript #geolocation #progressive-web-apps

Вопрос:

Моя цель-создать функцию в другом файле для импорта «getGeoLocation.ts», и это код:

 export default function getGeoLocation () {
    getLocationPromise.then((location:any) => {
        console.log(location);
        return location;
    }).catch((err) => {
        return err;
    })
}

let getLocationPromise = new Promise((resolve, reject) => {
    function success (position:any) {
        resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})
    }
    function error(err:any) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    }
    var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error, options)
    } else {
        reject("your browser doesn't support geolocation API")
    }
})
 

Я также попробовал версию без обещаний, которую я нашел в MDN:

 export default function getLocation() {
  
  var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  };

  function error(err:any) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
  }

  function success(pos:any) {
    var crd = pos.coords;
    return crd;
    console.log('Sua posição é:');
    console.log(`Latitude : ${crd.latitude}`);
    console.log(`Longitude: ${crd.longitude}`);
    console.log(`Precisão de ${crd.accuracy} metros.`);
  }

  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error, options);
  } else {
    alert("Geo Location not supported by browser");
  }
}
 

У обоих одна и та же проблема, я могу «console.log(местоположение)», но я не могу «вернуть местоположение»;
чтобы вызвать другой компонент(пример ниже), как я делаю в любой другой функции, возвращающей объекты, зачем?

   import getGeoLocation from '../utils/getGeoLocation';
  const location = getGeoLocation();
  console.log(location);
 

Ответ №1:

Единственным полезным уроком, который я смог найти, было следующее: https://norbertbartos.tech/blog/use-geolocation-api-with-react-hooks/

и решение кода состоит в том, чтобы создать крючок, сочетающий состояние использования и эффект использования:

 import { useState, useEffect } from 'react';

export const geolocationOptions = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 1000 * 3600 * 24
};

export default function useCurrentLocation () {
  const [location, setLocation] = useState<any>();
  const [error, setError] = useState('');

  const handleSuccess = (position:any) => {
    const { latitude, longitude } = position.coords;
    setLocation({latitude,longitude});
  };

   const handleError = (error:any) => {
    setError(error.message);
  };

  useEffect(() => {
    if (!navigator.geolocation) {
      setError('Geolocation is not supported.');
      return;
    }
    navigator.geolocation.getCurrentPosition(handleSuccess, handleError, geolocationOptions);
  }, []);

  return { location, error };
};
 

Тогда я могу вызвать любой другой компонент

 import useCurrentLocation from '../utils/useCurrentLocation';
const {location, error} = useCurrentLocation();
console.log(location?.latitude);
console.log(location?.longitude);