How to use Browser location in React application
prasanna-emmadi
Posted on July 15, 2022
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>
);
}
๐ ๐ช ๐
๐ฉ
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
javascript How to build a website using React and Rest APIs (React basics explained)
November 6, 2024