PASSWORD RESET

Your destination for complete Tech news

How to get the current location in React JS?

511 0
< 1 min read

To get the current location (latitude and longitude) in a React component, you can use the browser’s Geolocation API. Here’s how you can do it:

import React, { useState, useEffect } from 'react';

function CurrentLocation() {
  const [location, setLocation] = useState({ latitude: null, longitude: null });

  useEffect(() => {
    const getLocation = () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            setLocation({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            });
          },
          (error) => {
            console.error("Error getting location:", error);
          }
        );
      } else {
        console.error("Geolocation is not supported by this browser.");
      }
    };

    getLocation();
  }, []);

  return (
    <div>
      {location.latitude !== null && location.longitude !== null ? (
        <div>
          <p>Latitude: {location.latitude}</p>
          <p>Longitude: {location.longitude}</p>
        </div>
      ) : (
        <p>Fetching location...</p>
      )}
    </div>
  );
}

export default CurrentLocation;

In this example, the CurrentLocation component uses the useState and useEffect hooks to manage the location state. The useEffect hook retrieves the current location using the navigator.geolocation.getCurrentPosition() method. It sets the latitude and longitude in the state based on the position data.

The component then conditionally renders the latitude and longitude once they are available. If the location data is not yet available, it displays a message indicating that the location is being fetched.

Remember that the Geolocation API requires user consent and may not work in all browsers or environments. Also, make sure your application is served over HTTPS, as some browsers may not allow geolocation access over HTTP.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.