Working with Ruby Geocoder
One of the many interesting things about Rails is that the ability to work with Gems. In this article we’ll talk a but about one specific Gem: Ruby Geocoder. We’ll discuss what it does, how to install it and it’s capabilities.
Ruby Geocoder is a Gem that allows users to work with geographic data in their Rails app. Specifically, the user can use Geocoder to convert geographic coordinates, IP addresses as well as street addresses into one another. In other words, if your Rails app requires finding the latitude and longitude of a specific location Geocoder will convert the data. If you need to convert an IP address into a street address, Geocoder will do that too.
Here’s a visual example of what Geocoder can do using the following test site https://sitepoint-geocoder.herokuapp.com/places/new:
In the above example, we can add out location via latitude and longitude or via address or IP address. Once we enter that information, we get the following:
In the above example, we can see a Google map with Chicago as a map point, since I put Chicago in the previous screen. We could have used my IP address or latitude and longitude but I don’t know my current latitude and longitude off the top of my head…
To install the Geocoder Gem, first we have to install the Gem like so.
Next, in Rails, we have to set up the models as follows:
And finally we set up the controller and views in the following manner:
Geocoder is an extremely flexible Gem. You can use it with PostgreSQL, SQLite, MySQL and MongoDB. Geocoder supports mutiple languages. It works with several Geolocation services including: Google, Yahoo, Bing, Nominatim, Yandex.ru, FreeGeoIP, MaxMind and more.
Ruby Geocoder supports IP address, location and latitude and longitude conversion. It is straightforward to install as well as extremely flexible to use with different servers, languages and geolocation services. If you have a web app requiring geolocation services, Ruby Geocoder is probably a good fit.