javascript - HTML5 地理定位当前 GPS 位置的纬度和经度坐标放入变量中

标签 javascript html variables geolocation scope

我正在尝试利用 HTML5 的地理定位功能来获取用户当前的纬度和经度值。在研究并尝试从 StackOverflow 上的其他问题中获得答案之后,我似乎仍然误解了访问全局变量的概念。到目前为止我所看到的一切都表明范围存在问题。我正在使用的代码看起来像是在函数中使用函数。我当前正在运行以下代码:

<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;

function getPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude); 
}

getPosition();

该代码目前可以正常工作,它将信息记录到控制台。但是,如果我将代码更改为此,它似乎不起作用:

<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;

function getPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    currentLat = position.coords.latitude;
    currentLong = position.coords.longitude; 
}

getPosition();

console.log(currentLat + "," + currentLong);

它只是像我最初设置的那样返回 0。我已经搜索了很多关于全局变量的信息,但大多数在线资源(包括 StackOverflow)都表明,只要我不在函数内重新声明变量(或创建覆盖全局变量的局部作用域变量),我就可以访问这些变量)。

最佳答案

感谢 gro 的评论,我发现这个有效:

    window.onload = function(){
    navigator.geolocation.getCurrentPosition(function(position) {  
      window.currentLat = position.coords.latitude;
      window.currentLong = position.coords.longitude;
      window.currentLatLong = new google.maps.LatLng(currentLat,currentLong);
      init();
    });
}

function init() {
    // run code here and reference currentLatLong, currentLat and currentLong
}       

关于javascript - HTML5 地理定位当前 GPS 位置的纬度和经度坐标放入变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24467057/

相关文章:

html - css direct-child 选择器选择所有级别的所有 child

windows - cmd中的计算机名变量

javascript - 包含特定类的 div 的 jquery 选择器

javascript - jQuery 检查文件扩展名在 IE 中不起作用

javascript - 保存特定值时如何更改输入背景颜色和文本颜色?

javascript - Jquery Mobile Slider 更改事件

javascript - Jquery post success变量范围

jquery 对元素变量执行选择器

javascript - 当 JavaScript 生成的复选框发生变化时运行函数

javascript - 内联JS onclick函数调用错误