Java脚本回调修改变量 - Google api geocode

时间:2010-11-08 13:26:55

标签: javascript google-maps callback google-maps-api-3 geocoding

我正在使用Google的地理编码/ googlemaps api。我可以成功地对一个位置进行地理编码,并放置一个标记,但是我很难将lat / long放在回调函数之外的变量中

function init() {
var latLng = new Array();//Setup the cities lat + long in array

this.foo = 3;

function addGeo(me){//call back function
    me.foo = 2;
return function (results, code){
  var marker = new google.maps.Marker({
        map: map, 
        position: results[0].geometry.location
      });

  me.foo = 7;
  this.foo = 8;
    }
}

var geo = new google.maps.Geocoder();
geo.geocode( {address: 'London', region: 'UK'}, addGeo(this));


var map = new google.maps.Map(document.getElementById("full_map"));

var latLngBounds = new google.maps.LatLngBounds( );

//For each city, add its location to the boundry and add a marker in that location
for ( var i = 0; i < latLng.length; i++ ) {
    latLngBounds.extend( latLng[ i ] );

}

alert(this.foo);

map.setCenter(latLngBounds.getCenter( ));
map.fitBounds(latLngBounds);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);

}

这是我的完整代码,我可以获得addGeo(回调函数)来编辑foo变量,但不在返回的函数内,这将警告2(this.foo的值),我这样做来存储lat并且在latLong数组中很长,所以我可以使用googles latLngBounds。

非常感谢任何帮助。

编辑:

对于我感兴趣的任何人 me.latLngBounds.extend(结果[0] .geometry.location); me.map.fitBounds(的LatLngBounds); (在主要部分设置相关变量之后) 在unamed功能中,它就像一种享受。

1 个答案:

答案 0 :(得分:1)

geocode方法是异步(AJAX中的 A ),这意味着它将立即返回,而无需等待服务器的回复。< / p>

因此,地理编码回调仅在其余代码后执行(当服务器回复时)。
alert(this.foo)设置之前,您的foo会在收到回复之前运行。

您需要将使用响应的所有代码移动到回调中。