【问题标题】:Why is this HTML5 geolocation-dependent javascript code erring?为什么这个 HTML5 地理位置相关的 JavaScript 代码会出错?
【发布时间】:2012-03-20 04:50:05
【问题描述】:

我有一些取决于地理位置的 javascript 代码。

http://jsfiddle.net/8D6vz/

var myLat = 0.0;
var myLng = 0.0;

function setCurrentPosition(position) {
 myLat = position.coords.latitude;
 myLng = position.coords.longitude;
}

function errorOccured() {
 document.write("sorry, error occured :( ");
}

$(function() {
 navigator.geolocation.getCurrentPosition(setCurrentPosition, errorOccured);
 document.write(myLat + " " + myLng);
});

然而,这段代码仅仅产生

0 0

而不是

"client's latitude here" "client's longitude here"

为什么?

我使用的是谷歌浏览器,它肯定支持地理定位。我还允许我的浏览器跟踪我的位置。 ​

【问题讨论】:

    标签: javascript html geolocation w3c-geolocation


    【解决方案1】:

    GetCurrentPosition 是一个异步函数,你可以像这样使用它

    function GetGeolocation() {
    
    navigator.geolocation.getCurrentPosition(GetCoords, GetError);
    
    }
    function GetCoords(position){
    
      var lat = position.coords.latitude;
    
      var long = position.coords.longitude;
    
      var accuracy = position.coords.accuracy;
    
      alert('Latitude: ' + lat + ', Longitude: '+ long);
    
    }
    

    【讨论】:

      【解决方案2】:

      哦,我想我明白了。

      我相信

      navigator.geolocation.getCurrentPosition()
      

      是一个异步函数。因此,setCurrentPosition(position) 是在将纬度和经度值打印到屏幕上后调用的,它会打印原始值。

      【讨论】:

      • 嗯,这很尴尬。我回答了我自己的问题。我希望这个问题可以帮助其他遇到类似问题的人:) 另外,如果您有更好的答案或解释,请告诉我。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      相关资源
      最近更新 更多