2011-01-22 98 views
0

我有一个小脚本,从geoplugin获取位置...我想将返回的合作伙伴存储在一个我声明为全局的变量中......但由于某种原因,回调不会读取它。我如何使回调使用全局变量?jquery回调不使用全局变量

if(navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
     myLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 
    }, function() { 
     noLocation(); 
    },{timeout: 20}); 
} 
else if (google.gears) { 
    var geo = google.gears.factory.create('beta.geolocation'); 
    geo.getCurrentPosition(function(position) { 
     myLocation = new google.maps.LatLng(position.latitude,position.longitude); 
    }, function() { 
     noLocation(); 
    }); 
} 
else { 
    noLocation(); 
} 
function noLocation() { 
$.getJSON("http://www.geoplugin.net/json.gp?id=117.201.92.17&jsoncallback=?", 
    function(data) { 
     if (data != "" && data.geoplugin_latitude != "") 
      myLocation = new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude) 
     else 
      myLocation = new google.maps.LatLng() 
    }); 

}

出于某种原因,我想是因为异步调用它的...我可以克服这个问题一些如何?

+0

哪些变量是你谈论你的意思做的“它不会读它”? – casablanca 2011-01-22 21:06:52

回答

2

它看起来像是将它存储在全局变量“myLocation”中。但是,您可能试图在实际设置之前读取该值。异步调用的工作方式是立即返回,然后在将来的某个时候,它会在请求获得响应时调用回调函数。其余代码将在此期间继续运行。

尝试的“警报”分配给myLocation后,看是否被填充它:

myLocation = new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude) 
alert(myLocation) 
+0

它正在填充,但地图不显示nethng,因为我相信,因为setCenter已经执行,地图api不知道显示什么...... – Amit 2011-01-22 21:50:24