How can I pass this code snippet to localstorage?

Asked

Viewed 53 times

2

<script>

   navigator.geolocation.getCurrentPosition(function(position) {
      document.cookie = "mylat="+position.coords.latitude;
      document.cookie = "mylng="+position.coords.longitude;

})


var mylat = Number("<?php print_r($_COOKIE['mylat']); ?>");
var mylong = Number("<?php print_r($_COOKIE['mylng']); ?>");


var myLatLng = {lat: mylat , lng: mylong};
  • In this code snippet I see that you try to take the geolocation of the user but first define a last position found. Do you want to record that last position? What exactly do you want to record on localStorage?

  • I wish to store the user’s current position to then define his establishments of interest. I was able to do the Storage location, but when I go up on the ftp server it shows that I am in the middle of the sea, that is... the latitude and longitude are null or zeroed.

  • Where are you using localstorage exactly? in the code you posted only with cookies

1 answer

0

You should notice code in javascript is asynchronous and that mainly the type of geolocation request you are making from the user’s location uses a callback, therefore

function(position) {
    document.cookie = "mylat="+position.coords.latitude;
    document.cookie = "mylng="+position.coords.longitude;
}

Is being executed after

var mylat = Number("<?php print_r($_COOKIE['mylat']); ?>");
var mylong = Number("<?php print_r($_COOKIE['mylng']); ?>");

So, you’re probably only getting a position in the second run onwards. In addition to overwriting the variable document.cookie with longitude only.

To use localStorage you can use

navigator.geolocation.getCurrentPosition(function(position) {
  // esta função é executada apenas depois de conseguir a localização
  // o que pode acontecer depois do script fora desta função

  var coords = position.coords; // apenas para encurtar
  localStorage.setItem("mylat", coords.latitude); // gravar lat
  localStorage.setItem("mylng", coords.longitude); // gravar lng
  // mudar centro do mapa
  map.setCenter({lat: position.coords, lng: position.coords});
})

// posição padrão em caso de não existir última posição gravada
var defaultLocation = {lat: -9.919302, lng: -50.486085};


var mylat = localStorage.getItem("mylat")
if (mylat === null) { // em caso de não existir lat gravada
  mylat = defaultLocation.lng; // use a lat da localização padrão
}

var mylng = localStorage.getItem("mylng");
if (mylng === null) { // em caso de não existir lng gravada
  mylng = defaultLocation.lng; // use a lng da localização padrão
}

var myLatLng = {lat: mylat , lng: mylng};

// Assumindo que você está usando um mapa da Google Maps Javascript API em map:
map.setCenter(myLatLng);

Browser other questions tagged

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