【问题标题】:How to get the full street address via the geocoder gem?如何通过地理编码器 gem 获取完整的街道地址?
【发布时间】:2015-06-28 02:53:56
【问题描述】:

我正在使用geocoder 和 Google 来验证地址,并在它们被轻微修改时给我正确的值以及获取纬度和经度。我想我在这里的实现可能有点偏离,因为它感觉很笨拙,而且我发现有些地址缺少街道号码。

我从以下代码开始:

result = Geocoder.search(full_address_to_verify)
if result != []
  street_address = result[0].address_components[1]["long_name"]
  city = result[0].address_components[2]["long_name"]
  state = result[0].address_components[5]["long_name"]
  zip = result[0].address_components[7]["long_name"]
end  

我发现有时我会得到多个结果,所以我会选择第一个(上面的[0])。此外,我发现了一些奇怪之处,大部分时间result[0].address_components[1] 包含完整地址,包括街道号码,但有时它不包含,然后我必须添加result[0].address_components[0]。我还没有弄清楚这其中的韵律或原因。

我的最终目标是将美国街道号码 + 街道、城市、州和邮政编码字段检索到单独的变量中。

所以我的问题是,有没有更好的方法来检索地址,以便街道号码始终与路线正确关联?

从文档中,我并没有真正看到任何干净的方法,这些方法只会简单地为我提供所需的地址字段,而不会将数据从请求回复中的各个字段中提取出来......

【问题讨论】:

    标签: ruby google-maps google-maps-api-3 google-geocoder street-address


    【解决方案1】:

    晚会晚了几年。从 google 地理编码 API 中提取地址非常简单,但使用嵌套的 address_components 相当麻烦。

    幸运的是,geocoder gem 具有访问地址信息的内置方法。在docs 上阅读更多信息。

    【讨论】:

      【解决方案2】:

      没错,address_components 应该能让你做你想做的事。对于rhyme,可以参考this part of the documentation about address type

      Google Maps API 通过在此位置放置一个字符串来标记此字段属于哪种组件:

      result[0].address_components[i].types[0]
      

      你应该根据类型获取对应的值,而不是address_components的位置。

      这就是 Google 在他们的 Places Autocomplete API demo 中处理它的方式:

      var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
      };
      ...
      ...
        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-20
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 2017-06-14
        • 2018-10-20
        • 1970-01-01
        相关资源
        最近更新 更多