Google javascript maps getCurrentPosition

时间:2015-01-12 20:06:43

标签: javascript google-maps

我如何使用:

navigator.geolocation.getCurrentPosition()

获取当前位置的坐标。
这是谷歌网站的例子:

function initialize() {
 var mapOptions = {
   zoom: 6
 };
 map = new google.maps.Map(document.getElementById('map-canvas'),
     mapOptions);

 // Try HTML5 geolocation
 if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
       var pos = new google.maps.LatLng(position.coords.latitude,
                                   position.coords.longitude);

       var infowindow = new google.maps.InfoWindow({
            map: map,
            position: pos,
            content: 'Location found using HTML5.'
            });
        map.setCenter(pos);
      }, function() {
           handleNoGeolocation(true);
         });
 } else {
   // Browser doesn't support Geolocation
      handleNoGeolocation(false);
 }
}

我尝试将 var pos 部分替换为 myPos ,这是一个全局变量,但它不起作用。
我的意思是我总是在initialize()函数之后得到 myPos 未定义 在形式(窗口)加载时调用的初始化函数中获取纬度和经度navigator.geolocation.getCurrentPosition()的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

.getCurrentPosition()是一个异步函数,因此一旦有了这些坐标就会执行一个回调,例如。

navigator.geolocation.getCurrentPosition(function(position){
  console.log(position);
});

会给你这样的东西:

{
  "timestamp": 1421093714138,
  "coords":
    {
      "speed": null,
      "heading": null,
      "altitudeAccuracy": null,
      "accuracy": 20,
      "altitude": null,
      "longitude": -122.4091036,
      "latitude": 37.7837543
    }
}

在您传递.getCurrentPosition的回调中,您甚至可以更新变量,假设它们是事先声明的。我猜你的myPos变量未定义的原因是因为你连接谷歌地图API的方式存在问题。如果您没有使用谷歌地图,只想获得一个位置,您可以这样做:

var myPos;

navigator.geolocation.getCurrentPosition(function(position){
  myPos = position;
});

哦,并确保您允许网站访问您的位置。在Chrome中,您会在页面顶部找到一个栏,上面写着“< website url>想要使用您计算机的位置[拒绝] [允许]”

编辑:

有两件事是错的。您只能在回调函数范围内访问该变量 - 只有在该函数运行时才会定义tmpPos。如上所述,.getCurrentPositionasynchronous函数。这意味着它设置了一个获取地理定位的过程,但在此期间会做其他事情(在您的情况下,它会继续并尝试将其他变量更新为其尚未拥有的信息)。

此外,您正在调用自身内部的初始化函数,因此将创建一个永无止境的无限循环函数。要解决此问题,请尝试:

function initialize(){
navigator.geolocation.getCurrentPosition(function(position){
  // create the map here, because we only have access to position inside of this function
  // even if we store in a global variable, it only gets updated once this callback runs

  var currentPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}

initialize();