今天写代码的时候,把页面中放入了google api的函数,功能就是根据输入的地址,来查询该地址所在地经纬度。

以前写例子的时候,就是单独一个页面,然后几个function一调用就行了。今天做的这个呢,是2个页面,父画面,子画面。父画面是一个详细的客户信息画面,有详细的信息;子画面就是一个地址查询,可以根据邮编来查询地址,点击确定按钮就会把查询的地址传给父画面,同时子画面关闭。这个是原先的功能,今天在原有传值基础上,我增加了根据所取到地址,再得到经纬度,然后再传回父画面。这个时候问题就出现了,Google api的函数就是执行不了了。

就是这个方法:

getLocations(address, callback) none Sends a request to Google servers to geocode the specified address. A reply that contains status code, and if successful, one or more Placemark objects, is passed to the user-specified callback function. Unlike the GClientGeocoder.getLatLng method, the callback function may determine the reasons for failure by examining the code value of the Status field. (Since 2.55)

我们一般用的时候,可能会这么用
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(35.658517, 139.745493), 15);

var geocoder = new GClientGeocoder();

function moveAddress(address){
  geocoder.getLocations(address, showMap);
}

function showMap(locations){
  if (locations.Status.code == G_GEO_SUCCESS){
    for (var i = 0; i < locations.Placemark.length; i++){
      var lat = locations.Placemark[i].Point.coordinates[1];
      var lng = locations.Placemark[i].Point.coordinates[0];
      var point = new GLatLng(lat, lng)
      var marker = new GMarker(point);
      map.addOverlay(marker);
    }
  }else{
    alert("住所から緯度経度に変換できません");
  }
}
 

这上面的方法中function showMap(locations)这个函数我始终进不去,这是怎么一回事呢,把我郁闷坏了,这可是google的东西,自己又调不了。后来想到原先调用的时候一开始是可以的,但是当时我是这么用的
alert(1111);
moveAddress("北京");
alert(1111);

原先是可以的,后来我把alert删掉它就不好使了,但是看alert应该和程序没有关系呀。后来突然脑子不知道怎么想到,是不是因为打出alert,程序停在那里了,我只有点击弹出的对话框之后程序才能继续执行的缘故呢。我就把子画面关闭的那段代码注释了,结果事实证明我的猜测是正确的,可以取到值了!!个人估计getLocations(address, callback)这个方法应该像java里面的线程,不影响主程序运行,但是我去掉alert之后,主程序速度太快,还没有从Google服务器取得信息呢,我子画面就关掉了,所以一直进不去function showMap(locations)这个函数。后来我加个setTimeout,让子画面停3秒再关,这样总算暂时解决了这个问题。

唉,这个破问题折磨了我2个多小时,郁闷!!