Search code examples
ruby-on-railsgeocodingrails-geocoder

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. 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.


Solution

  • The @object you are working with is likely an instance of 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.

    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.

    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