将地理位置坐标放入数组中
Putting geolocation coordinates into array
我正在尝试将我在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 内容,意味着没有可能意外触发的内容。
相关文章:
- 如何创建一个谷歌地图地理坐标数组
- 如何从某个位置顺时针和逆时针循环数组
- 将javascript数组中的项移动到特定位置的有效方法
- 生成ACF标记位置的数组(元素列表后缺少])
- 基于javascript中位置的数组差异
- Javascript删除数组中某个位置之后的项
- 在数组中迭代时的JS循环位置
- 在两个位置显示数组中的随机单词
- Javascript 地理位置:将坐标存储在数组中
- 将地理位置坐标放入数组中
- 将地理编码器的位置保存到数组中
- 如何从保存在数组某个位置的JSON行访问属性
- Javascript 返回数组中“匹配”数组的位置索引
- 将数组传递给具有地理位置和样式的 Openlayers 3
- 如何找到与文本框值匹配的数组的位置号?
- Google Scripts从单元格中填充值数组及其位置
- 根据父数组的位置获取最后一个存在的子数组
- 带有静态变量的地理位置数组
- 我如何找到数组的位置,其中一个整数应该在Javascript中更有效地插入
- 如何使用Javascript将地理位置坐标存储到数组中