我想做的是使用 html5 地理位置查找用户的位置,并将纬度和经度坐标存储到数组中,以便进一步与谷歌地图和 sql 语句一起使用。当我尝试将它们放入数组并将其写入窗口时,没有显示任何内容或者它说它未定义。下面的代码只是向我显示它是否被放入数组中的一种方法。提前致谢!
<script>
var array = [];
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
array.push(lat, lon);
}
document.write(array);
</script>
最佳答案
管理同步功能很容易。您只需将所有代码放入另一个函数中,然后在成功部分中调用该函数即可。
//这就是你想要做的
错误
(这不起作用,因为它将在 getCurrentPosition 完成之前执行警报和“其他很酷的东西”代码。)*
var array = [];
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
array.push(lat, lon);
});
alert(array);
/* All of the other cool
stuff you are going to do
with the array /*
右
var array = [];
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
array.push(lat, lon);
locationCode()
});
function locationCode() {
alert(array);
/* All of the other cool
stuff you are going to do
with the array /*
}
关于javascript - 如何使用 Javascript 将地理位置坐标存储到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30407610/