1

I have the following code that takes the user's location from a google api, the detail I have is that the accuracy is too high, for example accuracy: 2600.670416166183, I don't know if someone knows how to solve this error, it would be very useful

const useGeoLocation = () => {
const [location, setLocation] = useState({
    loaded: true,
     coordinates: {
            lat: "",
            lng: "",
        },
    aceptacion: null,
});
const onSuccess = (location) => {
    console.log(location);
    setLocation({
        loaded: true,
        coordinates: {
            lat: resultado.location.lat,
            lng: resultado.location.lng,
        },
        aceptacion:1
    });
};

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=......`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
        let resultado = JSON.parse(this.responseText);
       let latitude = resultado.location.lat;
       let longitude =  resultado.location.lng;
       setLocation({
            loaded: true,
            coordinates: {
                lat: resultado.location.lat,
                lng: resultado.location.lng,
            },
            aceptacion:1
        });
        console.log(resultado);
        return resultado
      }
    }
    http.send();
}, []);

return location;
}; export default useGeoLocation;
Esteban RL
  • 23
  • 1
  • 5

1 Answers1

1

I think you are using the wrong API for your needs.

Google Geolocation API is used to get location from Wifi/Bluetooth/Cell Tower/IP informations. In your example you don't put any additional information in the body of your request, so google will only give geolocation based on the user's IP, which doesn't have a good accuracy.

If you want a better accuracy using this API, you have to provides Wifi or Bluetooth spots near the user (see documentation here), but I don't think that's what you want, so I think the best solution is to use navigator.geolocation.getCurrentPosition native function from all browsers, it will get location directly from the device (GPS/Wifi/Bluetooth) like there :

https://developers.google.com/maps/documentation/geolocation/overview

You can find examples here :

How do I get user's location via navigator.geolocation before my fetch executes in componentDidMount() in react.js?

How to get location information in react?

Aznhar
  • 610
  • 1
  • 10
  • 30