I use setitem(coordinates)
in a previous page that concerns latitude an longitude. I want the next page to use getItem()
but just the latitude but I didn’t get it.
First page
function storeCoordinates(location) {
const coordinates = {
lat: location.lat(),
lng: location.lng()
};
localStorage.setItem('coordinates', JSON.stringify(coordinates));
}
Next page
window.onload = function () {
var lat = localStorage.getItem('coordinates.lat');
var IR = (-75 * lat) + 5025;
var energie_pro = IR * 0.926 * 0.8 * 0.213 * 1.92 * 8;
document.getElementById('eco_3000').innerText = energie_pro;
}
2
Answers
You can’t access the property of the object in localStorage. You need to get the string out of storage, deserialise it to an object, then access its properties:
Also note the use of
addEventListener()
overonload
andconst
instead ofvar
in the above example.The error in the code can be found on this line:
var lat = localStorage.getItem('coordinates.lat');
You can only access local storage items with the key you set it with, in this case ‘coordinates’. An improved version of the code will be: