Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda