2012-03-21 192 views
2

这是一个简单的问题,我在对象中有下面的方法,为什么它返回undefined?返回undefined的Javascript对象方法?

var getGeoLocation = function() { 
      if (typeof(navigator.geolocation) != 'undefined') { 
       var test = navigator.geolocation.getCurrentPosition(function(position) { 
        var lat = position.coords.latitude; 
        var lng = position.coords.longitude; 
        return(new google.maps.LatLng(lat, lng));  
       }); 
      } 
     } 
var testFunction = function() {alert(getGeoLocation()); // returns undefined?} 

回答

6

这是因为navigator.geolocation.getCurrentPosition是异步的。 getGeoLocation函数在传递给getCurrentPosition的匿名回调函数已执行之前返回,并且由于getGeoLocation函数没有return语句,它将返回undefined

根据navigator.geolocation.getCurrentPosition在回调中的响应移动代码。

2

它返回未定义,因为getGeoLocation不返回任何东西。试试这个:

var getGeoLocation = function() { 
      if (typeof(navigator.geolocation) != 'undefined') { 
       var test = navigator.geolocation.getCurrentPosition(function(position) { 
        var lat = position.coords.latitude; 
        var lng = position.coords.longitude; 
        alert(new google.maps.LatLng(lat, lng));  
       }); 
      } 
     } 
var testFunction = function() {getGeoLocation()}; 
0
function GetCurrentLocation() 
      { 
       if (navigator.geolocation) { 
        navigator.geolocation.getCurrentPosition(function(position) { 

                  var point = new google.maps.LatLng(position.coords.latitude, 
                           position.coords.longitude); 
alert(point); 
       } 
       else { 
        alert('W3C Geolocation API is not available'); 
       } 
      } 

使用此代码。它会给你一个完美的结果。