【问题标题】:Reverse Geocoder Returning undefined反向地理编码器返回未定义
【发布时间】:2013-01-19 20:25:15
【问题描述】:

所以,我使用的是谷歌的反向地理编码器,所以我最初做的是输入一个地址,例如东京,然后我得到那个 latlng 将 latlng 放回地理编码器中以接收正确的位置名称但是相反,它只是返回未定义。我的代码是:

var geocoder = new google.maps.Geocoder();
var place = document.getElementById("location").value;
var name;
var place_latlng;
geocoder.geocode({'address' : place}, function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    place_latlng = results[0].geometry.location;
    addMarker(place_latlng);
  }
});
geocoder.geocode({'latLng' : place_latlng},function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    name = results[0].formatted_address;
  }
});

name 每次都未定义,有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: javascript html google-maps-api-3 google-geocoder


    【解决方案1】:

    Geocoder 是异步的,需要在其回调函数中使用 Geocoder 返回的数据(未测试):

    geocoder.geocode({'address' : place}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK){
        place_latlng = results[0].geometry.location;
        addMarker(place_latlng);
        geocoder.geocode({'latLng' : place_latlng},function(results, status){
          if (status == google.maps.GeocoderStatus.OK){
            name = results[0].formatted_address;
            alert("name = "+name);
          } else { alert("reverse geocode of "+place_latlng+ " failed ("+status+")"); }
        });
      } else { alert("geocode of "+place+" failed ("+status+")"); }
    });
    

    Example

    【讨论】:

    • 啊,这有效,当我调用警报时,它显示正确的地址,但是当我将名称添加到它显示未定义的表时,这与本地范围有什么关系变量?
    • 没有。您需要在回调函数(警报所在的位置)中使用 name 变量。
    • 添加了一个例子。您可能会发现需要处理所有结果以找到最佳结果(尝试使用“Delaware”)。
    • 是的,我想说我如何确定哪个是最好的结果?
    • 查看documentation,它指出:“地址按从最佳匹配到最小匹配的顺序返回。通常,更准确的地址是最突出的结果,就像在这种情况下一样。请注意,我们返回不同类型的地址,从最具体的街道地址到不太具体的政治实体,例如社区、城市、县、州等。如果您希望匹配更一般的地址,您可能希望检查结果[ ].types 字段。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多