Save user latitude and longitude in variables

Asked

Viewed 282 times

0

Good afternoon, I am doing some projects using the Google Maps API and wanted to know how to save the values of latitude and longitude of the user in a variable each, which will be used later in other functions, can anyone help me? I’m using the following code to get the location:

<!DOCTYPE html>
  <html>
    <body>
      <p id="demo">Clique no botão para receber sua localização em Latitude e Longitude:</p>
      <button onclick="getLocation()">Clique Aqui</button>
      
      <script>
      var x=document.getElementById("demo");
      function getLocation(){
        if (navigator.geolocation){
          navigator.geolocation.getCurrentPosition(showPosition);
        }
        else{
          x.innerHTML="O seu navegador não suporta Geolocalização.";
        }
      }
      function showPosition(position){
          x.innerHTML="Latitude: " + position.coords.latitude +
          "<br>Longitude: " + position.coords.longitude; 
      }
      </script>
      
    </body>

</html>

1 answer

3


If you want to capture coordinates only once and reuse on other pages one of the alternatives is to use the browser’s localStorage. You can also choose sessionStorage. Both store the information in key/value format. An example of how to use localStorage

var objetoCoordenadas = {
  lat: position.coords.latitude,
  lng: position.coords.longitude
}

Save to localStorage:

window.localStorage.setItem('coordenadas', 
JSON.stringify(objetoCoordenadas));

Recover values:

let coordenadasUsuario = 
JSON.parse(window.localStorage.getItem('coordenadas'));
console.log(coordenadasUsuario.lat);

Note that the object that stores the coordinates is converted to string when saving, and parsed to JSON when retrieving.

Here is more information:

https://www.w3schools.com/html/html5_webstorage.asp

https://tableless.com.br/guia-fácil-sobre-usar-localstorage-com-javascript/

  • Nuss, mt bound it went super right here, the links tbm helped mt , I saved kkkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.