Last Updated: February 25, 2016
·
1.842K
· michaelcarter

Customising your ruby geocoding actions!

Introduction

Geocoder is a Ruby gem that allows you to easily store location information about a particular set of objects, and then perform location related methods on them. For instance, finding out which other users are near a particular user.

Modifying Geocode Actions

For the scenario of a user assigning a city location in their profile, a typical geocoding action on an ActiveRecord model might look like this:

geocoded_by :city

This works fine if the city is unique, but what if another city by the same name exists in another country to the one our user is in, how will we specify the correct city?

Luckily ,the geocoded_by action takes a block with two parameters, the object we're geocoding (prof in the example below) and the set of the results returned by the geocode query (results):

geocoded_by :city do |prof,results|
  if result = results.select{|res| res.country_code == "GB" }.first
    unless (result.latitude.nil? || result.longitude.nil?)
      prof.latitude = result.latitude
      prof.longitude = result.longitude
    end
    result.coordinates
  end
end

You'll notice we're using the res.country_code method to select the first result from the UK (for an imaginary UK-only site in this case). So this code would then store the location of the first matching city in the UK.

More Info

Geocoder::Result::Base gives us several methods we can use to do similar filtering actions, including coordindates, latitude, longitude, state, province, state_code, province_code and country. Depending on which search provider you're using, you can also use some bespoke methods, all of which are detailed on in the source on Github. For more information with get started with Geocoder, see this great Railscasts post.