Update the item's location and retrieve the latitude

On the previous page, I used setitem(coordinates) to store latitude and longitude information. Now on the next page, I want to use getItem() to retrieve only the latitude, but I'm having trouble getting 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;
}

Answer №1

The mistake in the script is located on the following line:

let latitude = localStorage.getItem('coordinates.lat');

You are only able to retrieve local storage values with the exact key used when setting them, in this situation 'coordinates'. A more refined version of the script would be:

let coordinates = localStorage.getItem('coordinates');
const latitude = JSON.parse(coordinates)?.lat;

Answer №2

To access the property of an object in localStorage, you must first retrieve the string from storage, then deserialize it into an object before accessing its properties:

window.addEventListener('load', () => {
  const data = JSON.parse(localStorage.getItem('data'));
  const value = data?.value;

  if (!value)
    return; 
  
  // continue with your code...
}

Also, take note of using addEventListener() rather than onload, and using const instead of var as shown above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for addressing: Slight alignment discrepancy when utilizing CSS display:inline-block and setting text-align:center on the parent element

I'm new to building websites with HTML5, and I've encountered a frustrating issue. I'm attempting to center the items in a horizontal navigation bar at the top of my page, but it's not aligning as expected. The items are contained withi ...

Error message: Unchecked runtime error - Unable to retrieve data from the specified URL. The extension manifest must include permission to access this particular host. This issue is occurring in manifest

Can someone help me out? I keep on receiving the error messages Unchecked runtime.lastError: Cannot access contents of url. Extension manifest must request permission to access this host. and Unchecked runtime.lastError: Could not establish connection. Rec ...

Check for length validation including spaces in JavaScript

My code includes a functionality that calculates the length of characters in a text area using both JSP and JavaScript: <textarea class="textAreaLarge" id="citation" rows="20" cols="180" name="citation" ...

Searching for a document using the $eq operator in MongoDB within the context of Next.js - what is

In my Next.js code, I am fetching a document from MongoDB using a unique slug. Here is the code snippet: export async function getStaticProps(context) { const postSlug = context.params.postPage; const { db } = await connectToDatabase(); const posts ...

The CSS file that is defined first in the node.js HTML is the only one being utilized

Currently, I am incorporating CSS and JS files into my node.js/express application with the help of the ejs templating engine. Interestingly, while the JavaScript files are being successfully implemented, only the first included CSS file seems to be affect ...

Creating a text slider in Javascript with dual quote sets is a fun and interactive

I am looking to create a dynamic quotes text slider with two sets of data. For reference, check out the fiddle link here: https://jsfiddle.net/628r3t1h/ (function() { var quotes = $(".quotes"); var quoteIndex = -1; function showNextQuote( ...

Navigating within a Positioned Fontawesome Icon using CSS

I'm trying to make the font awesome icon only appear when hovering over an image, specifically in the top right corner, but I'm having trouble achieving this. Below is a sample code snippet that demonstrates the issue. // Get the modal var mod ...

Getting variables from different functions in Python can be achieved by using the return

I am trying to implement a feature where I can fetch a search term from the function getRandomVideo() and then use it in a jQuery statement. For example, if I get "Beethoven" as the search term from the variable searches, I want to use it to retrieve JS ...

Delay Time for Closing Sub Menus When Multiple Dropdowns are Opened

My issue involves a multi-level drop-down menu that is solely constructed using CSS. The problem I am facing is that there is a delay of one second before the drop-down closes when the mouse is moved away. This delay causes multiple drop-down menus to stac ...

I am unable to click on the navigation buttons in my bootstrap template

I've been working on turning a single page Bootstrap template into a multi-page layout. I duplicated the index page and modified them into services, among other things. Although I updated the href to point to these new pages, the navbar buttons are no ...

Struggling to set up the Sneat HTML theme - I'm unable to configure the config.js file

I recently began using the Sneat Theme for my project and everything was going smoothly until I tried to adjust the color scheme across the entire project. It appears that despite following the instructions in the config.js file, the changes were not takin ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Ways to implement the function provided in the website using javascript

Exploring the world of JavaScript functionality as a beginner, I am eager to try pasting dynamic data into HTML. I came across a helpful link providing instructions on how to achieve this using a table format. However, despite my best efforts, I am strugg ...

sending Ruby arrays to jQuery code in a Haml template within the Ruby on Rails framework

Implementing a Highcharts graph on a haml template using jQuery and javascript is my current task. Here's an example showcasing the standalone graph from the demo code on the HighCharts site: :javascript $(document).ready(function() { $("#tabs ...

Hidden body text occurs when the div element is set to be sticky at the bottom

I have been trying to resolve an issue with a sticky element at the bottom of a page using javascript/jquery. However, the sticky element is hiding the body text. I want to display all body text without it being hidden by the sticky element, but I can&apos ...

Is there a way for me to identify what deletes CSS classes from an element during the first page load?

On a page where an element (specifically, a TextBox) initially has two CSS classes assigned when it loads, something strange is happening. After the page renders and JavaScript runs, the class attribute of the input element mysteriously becomes empty. I c ...

Create a stunning design with Bootstrap 4 by incorporating a full-width background for both the table header and rows,

Bootstrap 4 offers a convenient table feature, but I'm having trouble aligning it with the design provided to me. The design requires full-width background colors for both the dark header (thead) and the light body (tbody), all while keeping the eleme ...

Most effective method to avoid updating a node_modules package

tag: After downloading and installing a node_module (npm package)... I have customized the internal files within the node_modules folder to better fit my requirements. Although using it as a node_module is most convenient for me, I am concerned that futur ...

``Why isn't the Bootstrap dropdown menu button displaying properly on a Leaflet map?

I am currently in the process of developing a LeafletJS Map integrated with Bootstrap buttons. I have successfully configured the map to be fullscreen and positioned the buttons on top of it. Below is the code snippet that I utilized for this setup: <! ...

Switch picture when hovering over button image

Looking for a solution where I have 2 images - one inactive and the other active. I want the inactive part of the image to change to active when someone hovers over it. Here are the pictures: I was able to achieve this using mapster, but it's not res ...