简体   繁体   English

Rails地理编码器gem反向地理编码地址格式定制

[英]Rails geocoder gem reverse geocoding address format customization

I am using the geocoder gem to reverse geocode a location given the latitude and longitude of an object. 我正在使用geocoder gem将给定对象的纬度和经度的位置反向地理编码。 This works great, however, I would like to change the result so that only the desired part of the complete address is shown. 这很好用,但是,我想更改结果,以便仅显示完整地址的所需部分。

In some specific cases, I only want to remove the last bit of the output, and so I am simply using something like: 在某些特定情况下,我只想删除输出的最后一位,所以我只是在使用类似以下内容的东西:

<%= @object.address.to_s.chomp(', USA') %>

for any given instance. 对于任何给定的实例。

However, I would like to know if there is a more dynamic option to return only the zip code, only the country, etc. 但是,我想知道是否有一个更动态的选项,仅返回邮政编码,仅返回国家等。

The @object you are working with is likely an instance of Geocoder::Result::Google . 您正在使用的@object可能是Geocoder::Result::Google的实例。

If you look at the docs for Geocoder::Result::Google you'll notice that there are several methods for accessing components of an address like zip code, country, etc. 如果您查看Geocoder::Result::Google的文档,您会注意到有几种方法可以访问地址的组成部分,例如邮政编码,国家/地区等。

Here are some examples 这里有些例子

address = @object.address
puts address.postal_code  #=> 10010
puts address.city         #=> Manhattan
puts address.state_code   #=> NY
puts address.country_code #=> USA

If the component you are looking for isn't available in a method you can use address_components_of_type directly. 如果您要查找的组件在某种方法中不可用,则可以直接使用address_components_of_type

puts @object.address_components_of_type(:street_number) #=> 1600

You can find the full list of components here: https://developers.google.com/maps/documentation/geocoding/intro#Types 您可以在此处找到组件的完整列表: https : //developers.google.com/maps/documentation/geocoding/intro#Types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM