2012-03-21 16 views
2

ここでは簡単な質問ですが、私はオブジェクト内に以下のメソッドを持っています。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は何も返さないため、undefinedを返します。代わりにこれを試してみてください:

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'); 
       } 
      } 

このコードを使用します。それはあなたに完璧な結果を与えるでしょう。

関連する問題