将地理位置坐标放入数组中

Putting geolocation coordinates into array

本文关键字:数组 地理位置 坐标      更新时间:2023-09-26

我正在尝试将我在watchPosition()期间收集的地理位置坐标放入一个数组中,以便以后可以计算出总距离。

我创建了一个新数组

 var mapArray;
 mapArray = new Array();

然后我在哪里分配我的纬度和经度,我将值放入数组

   document.getElementById("currentLat").innerHTML = (position.coords.latitude);
    document.getElementById("currentLong").innerHTML = (position.coords.longitude);
    document.getElementById("mySpeed").innerHTML = (speedValue.toFixed(1));
 mapArray.push(currentLat);
 mapArray.push(currentLong);//put values in array

然后我想输出它们以检查它是否有效,因此尝试将数组转换为字符串

 function getArray(){
 var outputData = mapArray.toString();
 document.getElementById("arrayresult").innerHTML = (outputData);
  }

谁能看出我哪里出了问题?目前,输出只是"HTML"。SpanElement],[object' 一遍又一遍。

谢谢。

如果你想使用数组,不要使用 new Array() ,改用数组文字[],然后我们可以一次性分配整个东西:

var mapArray = [
  position.coords.latitude,
  position.coords.longitude
];

但是,既然您已经有了方便的position对象,为什么不直接依靠它:

function showPosition(position) {
  // grab all the keys in position.coords
  var keys = Object.keys(position.coords);
  // and then map them to "key: value" strings
  var pairs = keys.map(function(key) {
    return key + ": " + position.coords[key];
  });
  // join them up with commas between them, and ONLY between them:
  var stringified = pairs.join(", ");
  // and then set that as our on-page container text
  document.getElementById("result").textContent = stringified;
}

当然,我们可以收紧它,因为它是相当简单的代码:

function showPosition(position) {
  var result = Object.keys(position.coords).map(function(key) {
                 return key + ": " + position.coords[key];
               }).join(", ");
  document.getElementById("result").textContent = result
}

我们在这里也使用textContent,以防万一position.coords包含有趣的键或值。将其设置为文本内容,而不是 HTML 内容,意味着没有可能意外触发的内容。