如何在javascript中从内部函数为外部变量赋值?

时间:2014-03-01 17:26:34

标签: javascript function variables scope

所以,我有这段代码:

function centermap(){
  var geocoder = new google.maps.Geocoder();
  var address = document.getElementById('office_address').value;
  var new_location = "";
  geocoder.geocode( {'address': address}, function(results, status, new_location) {
    if (status == google.maps.GeocoderStatus.OK) {
      new_location = results[0].geometry.location;
      console.log(new_location); // output is fine here
    }
    else {
      console.log("Geocode was not successful for the following reason: " + status);
    }
  })
  console.log(new_location); // output is "" - which is the init value
  return new_location // the returned object is also ""
};

$("input[id=office_address]").change(function(){
  var coordinates = new Array();
  var location = centermap();
  coordinates.push(location.geometry.location.lat());
  coordinates.push(location.geometry.location.lng());
  map.setView(coordinates, 14);
});

关于这里的范围,我没有得到什么?如何设置"外部" new_location是地理代码的结果? 请随意指出我对此的理解中的所有错误

编辑:我已经在thisthis上阅读了答案,但我没有设法做我想做的事。

1 个答案:

答案 0 :(得分:1)

正如有人在评论中指出的那样,geocode函数是异步的,所以一旦执行它就会返回没有任何值。 考虑这个工作流程:

...
geocoder.geocode( ... );
// this is executed straight after you call geocode
console.log(new_location);

...
...
// probably at a certain point here your geocode callback is executed
function(results, status, new_location) {
  if (status == google.maps.GeocoderStatus.OK) {
  ...
});

重要的是将回调函数传递给centermap

$("input[id=office_address]").change(function(){
  var coordinates = new Array();
  // pass a callback to execute when geocode get the results
  centermap(function (location){
    coordinates.push(location.geometry.location.lat());
    coordinates.push(location.geometry.location.lng());
    map.setView(coordinates, 14);
  });
});

function centermap(callback){
  var geocoder = new google.maps.Geocoder();
  var address = document.getElementById('office_address').value;
  geocoder.geocode( {'address': address}, function(results, status) {
    var new_location = '';
    if (status == google.maps.GeocoderStatus.OK) {
      new_location = results[0].geometry.location;
      console.log(new_location); // output is fine here
    }
    else {
      console.log("Geocode was not successful for the following reason: " + status);
    }
    // at this point we return with the callback
    callback(new_location);
 });
 // everything here is executed before geocode get its results...
 // so unless you have to do this UNRELATED to geocode, don't write code here 
};
相关问题