【问题标题】:Google Maps Geocoder inside for loop谷歌地图地理编码器内for循环
【发布时间】:2012-01-17 12:20:19
【问题描述】:

我有这段代码试图在谷歌地图中定位一组标记:

  for(var i = 0; i < postcodes.length; i++) {
    var address = postcodes[i].innerHTML +", uk";
    geocoder.geocode({'address': address}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          position: results[i].geometry.location,
          map: map,
          icon: image,
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
   });
 }

但是,这在我尝试设置位置时返回未定义。如果我在 results[#] 中使用数字 (0) 而不是变量 i ,它可以正常工作,但我无法遍历结果。有没有人遇到过这个问题?

谢谢,

【问题讨论】:

  • results[i] 是什么未定义?
  • @kmkemp:是的,具体来说:Uncaught TypeError: Cannot read property 'geometry' of undefined
  • 看kjy112在这个链接的回答:stackoverflow.com/questions/5292060/…

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


【解决方案1】:

问题是开始一个循环遍历邮政编码:

for(var i = 0; i < postcodes.length; i++) {

所以 i 是邮政编码数组中的索引。然后,您尝试在从您的邮政编码 [i] 的地理编码请求返回的结果对象中使用该索引;但是这两个数组是不相关的。变量 results 是 postcodes[i] 的结果,包含该邮政编码的所有搜索结果。因此,results[0] 是与一个邮政编码最接近的结果。

我想你想要的是:

for(var i = 0, num = postcodes.length; i < num; i++) { // loop through postal codes
  geocoder.geocode(
    {
      address: postcodes[i].innerHTML + ", uk"
    },
    function(results, status) {
      if (status != google.maps.GeocoderStatus.OK) {
        alert("Geocode was not successful for the following reason: " + status);
        return false;
      }
      for (var i = 0, num = results.length; i < num; i++) { // loop through results
        var marker = new google.maps.Marker({
          position: results[i].geometry.location,
          map: map,
          icon: image
        });
      }
    }
  ); // end geocode request
}

如果您只想显示最接近的结果,请省略第二个 for 循环并使用 results[0] 而不是 results[i]。

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多