1

我是 Javascript 的新手。我正在尝试使用 Google api 的 Gmap v3 来实现反向地理编码。我已经阅读了许多教程并编写了一个简单的代码。问题是传递给 geocoder.geocode() 的匿名函数有时有效,但有时无效。谢谢你的帮助!。

    function geoCode(latStr,lngStr){


      var lat = parseFloat(latStr);
      var lng = parseFloat(lngStr);
      var latlng = new google.maps.LatLng(lat, lng);

    codeLatLng(latlng,function(addr){
      alert(addr); // sometimes message appears.
    });
     }


  function codeLatLng(latlng,callback) {
      if (geocoder) {
        geocoder.geocode({'latLng': latlng}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
              callback(results[1].formatted_address);
            } else {
              alert("No results found");
            }
          } else {
            alert("Geocoder failed due to: " + status);
          }
        });
      }
    }
4

2 回答 2

0
var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'latLng' : position
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    address = results[1].formatted_address;
                    // alert("Wow ! Got it");
                } else {
                    // alert("No results
                    // found");
                    infowindow.setContent("No address found");
                }
            } else {
                // alert("Geocoder failed due
                // to: " + status);
                infowindow.setContent("Geocoder failed due to: " + status);
            }
            infowindow.setContent(address + '<br/>' + Timestamp);
        });

        infowindow.open(marker.get('map'), marker, this);
        currentInfoWindow = infowindow;

    });
}

一旦尝试使用上面的代码

于 2013-10-19T07:06:05.083 回答
0

我不确定 Google 服务是否会返回null或返回一个空数组,但为了安全起见,您可以使用以下方法检查两者:if (results && results.length > )。另外,您是否忘记了 Javascript 中的数组是从零开始的?你可能想要results[0]

if (results && results.length > 0) {
    callback(results[0].formatted_address);
} else {
    alert("No results found");
}

通过解释:if (results[1])如果“结果”是长度为 0 或 1 的数组,您的代码会崩溃,因此我猜测间歇性故障。

于 2013-10-19T00:35:22.863 回答