DEV Community

prasanna-emmadi
prasanna-emmadi

Posted on

How to use Browser location in React application

Hi

How to get user location from Browser navigator location api in a react component

const Map = (props) => {
  // get the location from geolocation
  const [latLng, setLatLng] = useState({
    lat: 0.0,
    lng: 0.0,
    isLoaded: false,
  });

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setLatLng({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            isLoaded: true,
          });
        },
        (error) => {
          alert(error);
        }
      );
    }
  }, [setLatLng]);

  const lat = "latitude is : " + latLng.lat;
  const long = "longitude is : " + latLng.lng; 
  return (
    <div>
      <p>{lat}</p>
      <p>{lng}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)