Search code examples
javascriptarraysjsongeolocation

Saving Geolocation to an array value returns [object, Object]


I've been trying to search a solution to this one, but I just can't find it.

I am writing a code which saves data to the browsers local storage as jSon. The code works fine but i should add geolocation to every data saved. I can get the coordinates to show in a div, but I am not able to save that same data to jSon -file.

The code goes 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 trying to get the 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();

  });

Clearly, I am trying to save the location data in a wrong form but how is it done correctly? Thank's for the help in advance!!


Solution

  • Your problem is with asynchronous requests.

    When you call getPosition(), you are calling getCurrentPosition(showPosition). The problem here is that this function executes asynchronously. Afer calling it, it runs in the background and your code continues executing without delay, so when you define the object variable, showPosition has not been called, and so x contains the initial value you gave it, which is a HTMLDivElement.

    To avoid this, you should define the object variable inside the showPosition callback, and save it from there, too, as you don't ever know when that method will be called. For starters, the user must give permission for the page to get their current location. The user can deny this, or ignore it, and in this case the callback function may never get called. I mean, you might know if there has been an error (getCurrentPosition accepts an error callback) but it is possible that you never receive an answer to your request.

    Besides, there are other problems with this code, because you are assigning x to a DIV element, and then you assign it to a string. I imagine you really want to add that string as a child node of the DIV, so you should do:

    x.appendChild(document.createTextNode('geolocalization is not supported in this browser'));