When I allow browser to get the Geolocation upon button Click, I am able to see the Latitude and Longitude. But when I block the site for accessing location, I am getting "Unable to retrieve your location" and Latitude and Longitude as well ... Here When I Block the site, I should get only message "Unable to retrieve your location" and Latitude and Longitude should not show...Please find the Screenshot as well
Here is my Code
const GeolocationButton = () => {
const [lat, setLat] = useState(null);
const [lng, setLng] = useState(null);
const [status, setStatus] = useState(null);
const getLocation = () => {
if (!navigator.geolocation) {
setStatus('Geolocation is not supported by your browser');
} else {
setStatus('Please allow brower to access your Location');
navigator.geolocation.getCurrentPosition((position) => {
setStatus(null);
setLat(position.coords.latitude);
setLng(position.coords.longitude);
}, () => {
setStatus('Unable to retrieve your location');
});
}
}
return (
<div className="App">
<button onClick={getLocation}>Get Location</button>
<h1>Coordinates</h1>
<p>{status}</p>
{lat && <p>Latitude: {lat}</p>}
{lng && <p>Longitude: {lng}</p>}
</div>
);
}
export default GeolocationButton
lat and lng are state variables, and state is, well, persistent. Consequently, when you set lat and lng, they retain those values, even if you later block access to location data.
There are various ways to resolve:
Since status, lat and lng are all interdependent, use a single state variable to store all three. This approach best realizes the dependent relationship between the variables.
const GeolocationButton = () => {
// could also initialize location to `{}`
const [location, setLocation] = useState({status:null,lat:null,lng:null});
const getLocation = () => {
if (! navigator.geolocation) {
// don't spread previous state into new state, and
// no need to explicitly set location.lat & .lng
setLocation({
status: 'Geolocation is not supported by your browser',
});
} else {
…
When setting status, also set lng and lat. This doesn't explicitly implement the interdependency between variables, and so requires more discipline on the part of the programmer.
if (! navigator.geolocation) {
setStatus('Geolocation is not supported by your browser');
setLat(null);
setLng(null);
} else {
// note: there's a typo in "browser" in the question sample
setStatus('Please allow browser to access your Location');
setLat(null);
setLng(null);
…
When getting the location, initialize lat and lng to null:
const getLocation = () => {
setLat(null);
setLng(null);
When displaying lat and lng, check that status isn't set (you should also check status before displaying it):
{status && <p>{status}</p>}
{!status && lat && <p>Latitude: {lat}</p>}