2014-02-28 212 views
1

我有以下代碼:在javascript函數返回值未定義

JS負載:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 

js函數:

<script type="text/javascript"> 

    var get_location; 

    function get_google_latlng() { 

     var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 'address': 'iran'}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       window.get_location = results[0].geometry.location.lat(); 
      } else { 
       window.get_location = status; 
      } 
     }); 

     return window.get_location; 
    } 

    var lat = get_google_latlng(); 

    alert(lat); 
</script> 

回報功能是undefined

window.get_location命令也不起作用。

+1

[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – elclanrs

+0

你想用'window.get_location'達到什麼目的?你認爲這是/是什麼? –

+0

嘗試使用「get_location」而不是「window.get_location」 – Selva

回答

2

你有什麼是異步功能的問題。您沒有立即獲取geocode方法的值,因爲您正在發出ajax請求並且需要時間。典型的JavaScript新手。

回調和封閉是技術的JavaScript編程時,將讓您的生活更輕鬆。我會建議你改變你的思維方式,這不是渦輪帕斯卡爾了。這是JavaScript。 async。不要指望每個函數立即返回結果。

與回調例子:

// Ugly global variable 
var get_location; 

// Even more ugly global function 
function get_google_latlng(callback) { 

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': 'iran'}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      window.get_location = results[0].geometry.location.lat(); 
     } else { 
      window.get_location = status; 
     } 

     // Now you invoke the callback to notify that the results are ready 
     callback(); 
    }); 

    // This is absolutely unnecessary 
    return window.get_location; 
} 

get_google_latlng(function(){ 

    // Only here we are sure the variable was actually written  
    alert(window.get_location); 
}); 

最後一兩件事,從來沒有,永遠永遠聲明函數和變量直接「窗口」下,JavaScript中的全局對象,這是一個反模式,這將使你在未來頭痛。

請了解如何使匿名函數。

+0

我想接收輸出。 –

+0

你可以在回調中做任何你想做的事情。這就是你「接收」輸出的地方。 –

+0

不輸出。 [jsfiddle](http://jsfiddle.net/mst404/fM2dL/) –

0

試試這個代碼:

var get_location; 
var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 'address': 'iran'}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      get_location = results[0].geometry.location.d; 
      alert(get_location); 
     } 
}); 

與您的代碼的問題是,是越來越執行先的get定位功能警報。

+0

我想收到輸出。我不想警惕。 –