0

我使用谷歌的地理编码/谷歌地图api。我可以成功地地理编码的位置,放置一个标记,但即时通讯有问题把经纬度/长在回调函数Java脚本回调修改变量 - Google api地理编码

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); 

} 

这就是我的全部代码之外的varible,我可以得到addGeo(回调函数)来编辑foo变量,但不在返回的函数中,这会提醒2(this.foo的值),我这样做是为了将lat和long存储在latLong数组中,这样我就可以使用google的latLngBounds。

任何帮助将不胜感激。

编辑:

对于任何intrested我把 me.latLngBounds.extend(结果[0] .geometry.location); me.map.fitBounds(latLngBounds); (在主要部分中设置相关变量之后) 在unamed函数中,它就像一个款待。

+0

如果API迫使您在回调中获取返回的值而不是从函数返回,那么您认为没有理由吗? – SLaks 2010-11-08 13:30:06

回答

1

geocode方法是异步(所述在AJAX),这意味着它会立即返回,而无需等待来自服务器的应答。

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

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

+0

这是否意味着我需要做其他事情,(存储在DOM或XML文件等?) – akd5446 2010-11-08 13:30:25

+0

@akd:你明白发生了什么事? – SLaks 2010-11-08 13:31:36

+0

我想我是这样做的,在回拨过程中移动它的问题是我需要对3-4个位置进行地理定位。 – akd5446 2010-11-08 13:34:43