简体   繁体   中英

Can't pass coordinates through localstorage

I'm trying to make a Google Maps application, where you can enter you location in an input and then get redirected to another page with a map that shows your location. The problem is that when I'm saving the coordinates in a localstorage on one Javascript file its not able to read it out on the other one. Any ideas?

Heres my Code

Saving data:

 var location = document.getElementById('location-input').value;
axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    params:{
        address:location,
        key:'AIzaSyBsOGGokaWGD3m5y4uYYG_sv7U1T9nZ5HI'
    }
})
.then(function(response) {
    // Log full response
    console.log(response);

    var lat = response.data.results[0].geometry.location.lat;
    var lng = response.data.results[0].geometry.location.lng;

    sessionStorage.setItem('lat', lat);
    sessionStorage.setItem('lng', lng)

    console.log(lat)
})
.catch(function(error) {
    console.log(error);
})`

Retrieving data:

function initMap(){
var lat = sessionStorage.getItem('lat');
var lng = sessionStorage.getItem('lng')
console.log(lat)
})}

I want to add that passing a number directly or passing a word is no problem.

lat & lng are functions of a google.maps.LatLng . Call them to get the value:

var lat = response.data.results[0].geometry.location.lat();
var lng = response.data.results[0].geometry.location.lng();

live proof of concept:

better to encode your data before pssing them

var coord = JSON.stringify({
  lat :  response.data.results[0].geometry.location.lat();
  lng  : response.data.results[0].geometry.location.lng();
});
sessionStorage.setItem('coord', coord);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM