2014-02-28 132 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

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