Reputation: 79
i am building a very simple app that requires the geo-location of visitors. I use the react navigator geoLocator for this. My desired behavior is to show the gps coordinates when permission has been granted and show a custom "needs location" screen when location permission is not granted or is revoked. It works perfectly on the desktop, but when I visit the website on mobile, the location permission is never requested.
Here is my custom hook that gets location:
import { useState, useEffect } from "react";
const useGeoLocation = () => {
const [location, setLocation] = useState({
loaded: false,
coordinates: { lat: "", lng: "" },
});
const onSuccess = (location) => {
setLocation({
loaded: true,
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude,
},
});
};
const onError = (error) => {
setLocation({
loaded: true,
error: {
code: error.code,
message: error.message,
},
});
};
useEffect(() => {
// if the browser does not support geo-location (unlikely)
if (!("geolocation" in navigator)) {
onError({
code: 0,
message: "Geolocation not supported",
});
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}, []);
return location;
};
export default useGeoLocation;
And then here is my App.js:
import './App.css';
import useGeoLocation from './custom_hooks/useGeolocation';
import CircularProgress from '@mui/material/CircularProgress';
import NoLocation from './components/NoLocation'
function App() {
const location = useGeoLocation();
return (
<div className="App">
{location.loaded ? <div>{location.coordinates ? JSON.stringify(location.coordinates) : <NoLocation />}</div> : <CircularProgress style={{color: '#d500f9'}} />}
</div>
);
}
export default App;
I am not entirely sure why it does not work appropriately when I visit the website from mobile
QUESTION: What is the right way to test on mobile so I can retrieve location without having to deploy the app?
Upvotes: 0
Views: 2588
Reputation: 21
What I have observed is that chrome mobile browser is not allowing to enable location on sites not having HTTPS layer as it exposes sensitive information to attackers. So in case of localhost it runs on http so it is not allowing the location to be enabled. But codesandbox has https layer so it is allowing the site to request for the location. I don't know whether my answer is correct or not and please correct me if I'm wrong :)
Upvotes: 2