2010-10-04 47 views
0

我试图做一些事情,应该是很简单 - 但它做我的头 我似乎无法得到一个变量从一个函数返回使用Javascript - 返回变量失败

var where; 
if (navigator.geolocation) { 
    where = navigator.geolocation.getCurrentPosition(function (position) { 
    // okay we have a placement - BUT only show it if the accuracy is lower than 500 mtrs 
    //if (position.coords.accuracy <= 500) { 
     // put their lat lng into google 
     var meLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
     var image = "images/map_blue.png"; 
     var myMarker = new google.maps.Marker({ 
      position: meLatLng, 
      map: map, 
      title: "Your location, as provided by your browser", 
      icon: image, 
      zIndex: 50 
     }); 
    //} // end 500 mtrs test 
      return meLatLng;   
    }); 
    alert("A: "+where); 
} 

我有一个名为全局变量在哪里,我想用navigator.geolocation从浏览器接收经纬度信息,以填补它 - 它绘制在地图上的用户 - 但警报(在哪里)总是返回undefined

什么我做错了吗?

回答

3

简短的回答,没有,

时间长一点的回答,嗯......你看,问题是,它会显示你的匿名函数返回其值的getCurrentPosition功能,这似乎犯规在返回任何东西所有。

为了使用返回的值,你应该使用回调或处理数据的地方是......

简单地尝试customCallBack(meLatLng)更换return meLatLng,然后定义customCallBack某处沿线。

或者,因为你已经在全球范围内定义where你可以尝试用where = meLatLng取代return meLatLng,然后从where = navigatior.geoloc....

删除where =如果我的怀疑是正确的,最后一种方法不会工作,因为我相信getCurrentPosition是异步的,这意味着您在调用应用程序后立即离开应用程序的标准流程。这就是为什么你首先提供一个函数。

+0

是的,它似乎它用完主流,所以我不得不看看这个CallBack的想法..谢谢:) – keranm 2010-10-04 18:40:01