2012-03-21 86 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'); 
       } 
      } 

使用此代碼。它會給你一個完美的結果。