【发布时间】:2014-06-15 14:47:56
【问题描述】:
我正在构建一个小型 Web 应用程序,它采用表单输入(名称)+ 用户的地理位置并将其放入本地存储数组中。我是 JS 的新手,但我已经完成了负责名称的部分。我现在正试图将它扩展到在用户按下提交时将纬度 + 经度存储在本地存储数组中的点,但不知何故,执行此操作的函数不会启动/设置。
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var lat = JSON.parse(localStorage.getItem('latitude') || "[]");
var long = JSON.parse(localStorage.getItem('longitude') || "[]");
function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(saveData);
console.log('This works');
} else {
showError("Your browser does not support Geolocation!");
}
}
function saveData(data){
console.log('But does it get here?');
//Push Users Input value
var data = document.getElementById("locationName").value;
names.push(data);
localStorage.setItem('locname', JSON.stringify(names));
//Push Latitude
var latitude = position.coords.latitude;
lat.push(latitude);
localStorage.setItem('latitude', JSON.stringify(latitude));
//Push Longitude
var longitude = position.coords.longitude;
long.push(longitude);
localStorage.setItem('longitude', JSON.stringify(longitude));
}
document.querySelector('#saveData').onclick = initCoords;
}
我有一个 ID 为 saveData 的按钮。我没有地理定位的这个脚本的早期版本运行良好,在那里我通过单击按钮启动了 saveData 功能。在这种情况下,我首先想检查用户是否有可用的地理位置,因此我创建了 initCoords 函数。
我尝试使用控制台日志来查看我的函数在哪里结束,它以某种方式没有到达 saveData 中的“但它到达这里”。
【问题讨论】:
标签: javascript html geolocation