skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    var coordinates = localStorage.getItem('coordinates');
    const lat = JSON.parse(coordinates)?.lat;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search