How to use Browser location in React application

prasannaemmadi

prasanna-emmadi

Posted on July 15, 2022

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
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
prasannaemmadi
prasanna-emmadi

Posted on July 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About