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

213
Vistas
How to get current location without clicking the button in ReactJS?
//*some code
 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('Locating...');
           navigator.geolocation.getCurrentPosition((position) => {
                setStatus(null);
                setLat(position.coords.latitude);
                setLng(position.coords.longitude);
           }, () => {
                setStatus('Unable to retrieve your location');
           });
      }
 }
 const point = {
      lat: lat,
      lng: lng
 };
 const dest = {
      lat: 123,
      lng: 456
 };
//*some code

I got the reference from here https://javascript.plainenglish.io/how-to-use-the-geolocation-api-in-your-react-app-54e87c9c6c94

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Add useEffect hook and call getLocation function inside it.

  const [lat, setLat] = useState(null);
  const [lng, setLng] = useState(null);
  const [status, setStatus] = useState(null);

  useEffect(() => {
    getLocation();
  },[]);

  const getLocation = () => {
       if (!navigator.geolocation) {
            setStatus('Geolocation is not supported by your browser');
       } else {
            setStatus('Locating...');
            navigator.geolocation.getCurrentPosition((position) => {
                 setStatus(null);
                 setLat(position.coords.latitude);
                 setLng(position.coords.longitude);
            }, () => {
                 setStatus('Unable to retrieve your location');
            });
       }
  }
about 4 years ago · Juan Pablo Isaza Denunciar

0

try this one. Previously findNearestLocation function was called before set latitude and longitude. At that moment mylocation was null. That was the reason.

import React, { useEffect, useState } from 'react'
import findNearestLocation from 'map-nearest-location';

export default function App() {
 const [myLocation, setMylocation] = useState(null);
 const [nearestLocation, setNearestLocation] = useState(null);
 const [status, setStatus] = useState(null);

 const locations = [
     {
       lat: 40.7722691,
       lng: -74.3008176
     },
     {
       lat: 40.682638,
       lng: -73.941015
     },
     {
       lat: 40.870347,
       lng: -74.105810
     },
     {
       lat: 40.7374197,
       lng: -74.2719785
     }
   ];

 useEffect(() => {
      getLocation();
 }, []);

 useEffect(() => {
     if(myLocation) {
          const nearest = findNearestLocation(myLocation, locations);
          setNearestLocation(nearest);
     }
 },[myLocation]);

 const getLocation = () => {
      if (!navigator.geolocation) {
           setStatus('Geolocation is not supported by your browser');
      } else {
           setStatus('Locating...');
           navigator.geolocation.getCurrentPosition((position) => {
                setStatus(null);
                setMylocation({
                     lat: position.coords.latitude,
                     lng: position.coords.longitude
                })
           }, () => {
                setStatus('Unable to retrieve your location');
           });
      }
 }

 console.log(nearestLocation);

 return (
      <div className="App">
           <h1>map here</h1>
      </div>
 )
}
about 4 years ago · Juan Pablo Isaza 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