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.