0

Geocoding in Rails

Geocoding-blog.jpg

Place-based services are very popular now-a-days in mobile and web world. Showing and fetching data from map(eg. google map, bing) brings coolness in any application. In rails, there is a handy gem named geocoder to do so.

Geocoding:

Geocoding is a process in the computational world in which an address is converted to a location on the earth surface. This location is mostly consists of longitude and latitude and this location can be represented in map. There is another term named reverse geocoding which clearly implies the opposition of geocoding.

Geocoder:

Like any other gem, we can install this gem by simply adding gem "geocoder in gemfile and doing bundle install. Next we have to do is adding this geocoder in model.

Suppose we have a model named Hospital. We wanna do geocoding on this type of objects. Firstly we have to add latitude and longitude attribute in model by rails migration. Next the model must have the capability to ask for geocoded address. We can do this by adding

app/model/hospital.rb

 geocoded_by :address   # address is attribute
 after_validation :geocode

Ok we are ready to go now. There are many methods that gives us ease of finding other objects around an object. We will talk about 2 of them.

Firstly, We are going to say about near. Its a class method which take an geocode object or latitude, longitude array or any address as a centre and a distance as radius and then gives us the array of objects sorted by distace from that centre point which is situated in radius of that distance. Some samples are

Hospital.near("panthopoth, Dhaka, Bangladesh",20)

Hospital.near([25.33, 86.67], 20)

Hospital.near(@hospital,20)

By the way all the distance are in miles by default. If we need other ubt like kilometre. we have to add units: "km" inside near.

Lastly we gonna learn about nearbys. The task of this is same as the near but its a instance method. That means we have to take geocode object to use this. This method only takes a distance as radius. Rest is same as near method. Sample is

@hospital.nearbys(20)

We have just learnt about some basic about geocoder gem. But its use is vast. You can know its advanced use in here.

Happy geocoding.

Ha5


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí