将Geolocation保存到数组值将返回[object,Object]

时间:2018-03-15 10:40:45

标签: javascript arrays json geolocation

我一直在尝试搜索这个解决方案,但我找不到它。

我正在编写一个代码,将数据作为jSon保存到浏览器本地存储中。代码工作正常,但我应该为每个保存的数据添加地理位置。我可以在div中显示坐标,但是我无法将相同的数据保存到jSon -file。

代码如下:

$(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();

  });

显然,我正在尝试以错误的形式保存位置数据但是如何正确完成?感谢提前帮助!!

1 个答案:

答案 0 :(得分:0)

你的问题在于异步请求。

当您致电getPosition()时,您正在呼叫getCurrentPosition(showPosition)。这里的问题是这个函数执行异步。在调用它之后,它会在后台运行并且您的代码会毫不拖延地继续执行,因此当您定义object变量时,showPosition尚未被调用,因此x包含初始值你给了它,这是一个HTMLDivElement

要避免这种情况,您应该在showPosition回调中定义object变量,并将其保存在那里,因为您不知道何时会调用该方法。对于初学者,用户必须授予页面获取其当前位置的权限。用户可以拒绝这一点,或者忽略它,在这种情况下,回调函数可能永远不会被调用。我的意思是,您可能知道是否存在错误(getCurrentPosition接受错误回调),但您可能永远不会收到对您的请求的回答。

此外,此代码还有其他问题,因为您要将x分配给DIV元素,然后将其分配给字符串。我想你真的想把这个字符串添加为DIV的子节点,所以你应该这样做:

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