Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
When I Block the Site , Still I am able to see the geolocation of the Browser using Reactjs

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 wellenter image description here

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
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

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:

  1. 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 {
                 …
    
  2. 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);
        …
    
  3. When getting the location, initialize lat and lng to null:

     const getLocation = () => {
        setLat(null);
        setLng(null);
    
  4. 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>}
    
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda