2012-01-02 76 views
2

所以我如何在函数内部的javascript函数外返回一个变量?

function find_coord(lat, lng) { 
       var smart_loc; 
     var latlng = new google.maps.LatLng(lat, lng); 
     geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 'latLng': latlng }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       smart_loc = new smart_loc_obj(results); 
      } else { 
       smart_loc = null; 
      } 
     }); 

     return smart_loc; 
} 

我想返回smart_loc变量/对象,但它始终是零,因为函数的范围(结果状态)没有达到在find_coord函数声明的smart_loc。那么如何在函数内部得到一个变量(结果,状态)呢?

+1

我不认为这是范围问题。而是一个我还没有定义的问题。 geocoder.geocode的作用是什么?像一个AJAX调用? – PeeHaa 2012-01-02 03:30:25

+3

你不能那样做。 “geocode()”函数是** asynchronous **,这意味着它不会立即运行;它在Google返回结果时运行。 – Pointy 2012-01-02 03:33:05

+0

,但该地理编码在该功能运行之前不会运行,而地理编码来自Google地图地理编码器 – Derek 2012-01-02 03:37:41

回答

0

你可以这样做:

var smart_loc; 

function find_coord(lat, lng) { 
    var latlng = new google.maps.LatLng(lat, lng); 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'latLng': latlng }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      smart_loc = new smart_loc_obj(results); 
     } else { 
      smart_loc = null; 
     } 
    }); 
} 

或者,如果你需要运行一个功能时smart_loc变化:

function find_coord(lat, lng, cb) { 
      var smart_loc; 
    var latlng = new google.maps.LatLng(lat, lng); 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'latLng': latlng }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      smart_loc = new smart_loc_obj(results); 
     } else { 
      smart_loc = null; 
     } 

     cb(smart_loc); 
    }); 
} 

然后调用:

find_coord(lat, lng, function (smart_loc) { 
    // 
    // YOUR CODE WITH 'smart_loc' HERE 
    // 
}); 
相关问题