Why did I get [object HTMLParagraphElement] for value of variable(geolocation)

Viewed 68

Here is the code which will get users coordinate and save the coordinates in local storage but it displaying [object HTML Paragraph Element] as stored value if i can save it as numeric value it would be easy to export i am a newbee please help me to solve this problem

var x = document.getElementById("demo");
var k = document.getElementById("demon");

localStorage.setItem("cor",k);

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
      } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";

  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
 k.innerHTML =position.coords.latitude
   
}
<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>
<p id="demon"></p>

</body>
</html>

1 Answers

LocalStorage only stores items as string values. So

localStorage.setItem("cor",k);

converts k (an HTMLParagraphElement) to a string, " [object HTML Paragraph Element]" in your browser, and saves it as item "cor".

To save the coordinates, try converting them to a JSON string, after obtaining them in the showPosition callback, by calling JSON.stringify with a coordinate object as argument:

function showPosition(position) {
  const {latitude, longitude} = position.coords;
  // save in local storage:
  localStorage.setItem("cor",JSON.stringify({latitude, longitude});
  // as posted:
  x.innerHTML = "Latitude: " + latitude + 
  "<br>Longitude: " + longitude;
  k.innerHTML =position.coords.latitude
   
}

To read the coordinates back again, pass the string value of getItem("cor") to JSON.parse to re-create the {latitude, longitude} object.

Related