Getting the map coordinates of an address in Ruby on Rails

Getting the map coordinates of an address in Ruby on Rails

If you’re developing a map-based application, something very interesting (and useful) is to get the map coordinates (latitude, longitude) from a given address.

To do this you can use the Geocoder gem. With this gem, apart from getting the map coordinates from an address, you can also calculate the distance between two points, get the address from a given coordinate, get venues close to an address and more. I encourage you to read the complete documentation following the next link:

https://github.com/alexreisner/geocoder

To start with, install the gem by executing the following command:

gem install geocoder

or adding the next line to your gemfile:

gem "geocoder"

followed by a

bundle install

Now that we have the gem correctly installed, is very easy to get the map coordinates from an address. Simply add the following line to your method:

location = Geocoder.coordinates("18 de Julio 1234, Montevideo, Uruguay")

The result is an array with the latitude in the first position and the longitude in the second one ( [lat, long] ).

The only parameter for the Geocoder.coordinates method is the address just like you would write it in Google Maps, or any other map service (you can choose the map service to use).

Valid examples for addresses are:

18 de Julio 1234, Montevideo
18 de Julio 1234, Montevideo, Uruguay
1234 18 de Julio, Montevideo

 

Leave a Reply

Your email address will not be published. Required fields are marked *