2012-07-19 302 views
0

如何获得创建对象之外的经度和纬度? 我已经做了Ext.util.Geolocation的新对象,更新了它,现在我试图让纬度和经度值在对象之外,但是它显示我'null'。 代码:Sencha Touch 2 Ext.util.Geolocation

var geo = Ext.create('Ext.util.Geolocation', { 
    autoUpdate: false, 
    listeners: { 
     locationupdate: function(geo) { 
      //alert('New latitude: ' + geo.getLatitude()); 
     }, 
     locationerror: function(geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) { 
      if(bTimeout){ 
       alert('Timeout occurred.'); 
      } else { 
       alert('Error occurred.'); 
      } 
     } 
    } 
}); 

geo.updateLocation(); 
//geo.fireEvent('locationupdate'); 

alert(geo.getLatitude()); // it shows null 

在此先感谢。

+0

尝试使用geo.updateLocation(); – Multitut 2012-10-11 17:35:02

回答

1

这可能是因为它需要一些时间来获得您的位置。

您应该尝试获取locationupdate回调函数内的经度和纬度。

如果你想外面访问它,只要确保地理存在

if (geo) { alert(geo.getLatitude()); } 

希望这有助于

+0

警报显示'null'。 – kmb 2012-07-25 13:51:44

+0

同样在这里。对此有过答案吗? – Multitut 2012-10-11 17:28:31

+0

在第一次更新发生之前,您无法确定geo不等于null,因此无论您想在locationupdate回调函数中执行什么操作。 – 2012-10-11 17:48:57

0

这只是一个时间问题 - 获得位置是不同步的,所以你不能在locationupdate回调函数之外访问它,至少在它被初始化之前。

你应该做你需要一个回调里面做(如呼叫传递,如果它需要纬度其他功能)...

... 
    listeners: { 
     locationupdate: function(geo) { 
      yourCallbackFunction(geo.getLatitude()); 
    }, 
    ... 

如果你真的需要使用该回调之外,则在最坏的情况下,你可以这样做:

var latitude; //will store latitude when ready.. 
var geo = Ext.create('Ext.util.Geolocation', { 
    autoUpdate: false, 
    listeners: { 
     locationupdate: function(geo) { 
      latitude = geo.getLatitude(); 
     } 
    } 
}); 
geo.updateLocation(); 

//waits until latitude exists then does something.. 
var untilLatThere = setInterval(function(){ 
    if(latitude) { 
     alert(latitude); //alerts a valid value.. 
     clearInterval(untilLatThere); 
    } 
}, 100);