Search code examples
javascripthtmlcss

setItem coordinates and getitem lat


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;
}

Solution

  • 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:

    window.addEventListener('load', () => {
      const coordinates = JSON.parse(localStorage.getItem('coordinates'));
      const lat = coordinates?.lat;
    
      if (!lat)
        return; 
      
      // rest of your code...
    }
    

    Also note the use of addEventListener() over onload and const instead of var in the above example.