I've been searching everywhere for a solution to this problem, but it seems elusive.
My current code saves data to the browser's local storage as jSon, and it works perfectly. However, I need to incorporate geolocation into each piece of saved data. While I can display coordinates in a div, I'm struggling to save that same data to the jSon file.
The code snippet looks like this:
$(document).ready(function(){
var selected_index = -1;
var theArray = [];
var operation = "A";
if(localStorage.getItem("ID") != null) {
}
//***********************************************************************
$("#saveButton").click(function(){
if(operation == "A" && $("#input1").val() != ""){
//Now attempting to obtain geolocation
var x = document.getElementById("DivId"); //works when targeted to a div
alert(x); //This returns [object
HTMLDivElement]
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
getLocation();
var object = {
value1 : $("#input1").val(),
value2 : $("#input2").val(),
value3 : $("#input3").val(),
value4 : $("#input4").val(),
value5 : $("#input5").val(),
time : Date(),
place: x //This is where the location is saved
//but returns [object, Object]
}
theArray.push(object);
localStorage.setItem("ID",JSON.stringify(TheArray));
}
console.log(x); //for testing, returns: <div id="DivID"
style="display: none;"></div>
$("#input1").val("");
$("#input2").val("");
$("#input3").val("");
$("#input4").val("");
$("#input5").val("");
$("#input1").focus();
});
It's clear that I'm storing the location data incorrectly. What would be the correct approach? Thank you in advance for any assistance!