Geocoder has plenty of methods to make a developer’s life easy when it comes down to the things like distance, nearby locations, directions, IP addresses etc, and why should it not, after all – it’s all about geo locations.
Geocoder adds methods to request to get the current IP location, and the stuff like this:
To get your IP address:
To get your location:
# It returns a Geocoder::Result which corresponds to your location
Not only this, you can fetch the city of your location as well through the following method.
Caution: Since, on your local machine the IP address is most of the time going to be 127.0.0.1, so the above discussed functionality won’t work efficiently there. You can deploy your app to Heroku, or any other remote platform to have a better understanding of this thing.
Calculating distance between two locations on a map carries huge importance. Sometimes, we’d like to find the objects manually, and differentiate them based on how far they are apart from a particular location. If this is the case, the following method will get you covered:
distance = @house.distance_from([@old_house.latitude, @old_ house.longitude])
The object @house must be a geocoded object, and the same is true for @old_house object. You can pass different options in it regarding distance unit and the other stuff. For more information regarding how to calculate distance in Geocoder gem, please head over to its documentation at this link.
If you add Geocoder gem after you have created your models, Geocoder will still help you do the job. It has a rake task that is going to help you geocode all the objects that have been created earlier, without having you manually write any code for this particular task.
rake geocode:all CLASS=House
Geocoder gem also provides you a scope to get all the objects as they haven’t been geocoded or objects without coordinates. Here are the two methods in this regard:
House.geocoded # To get objects with coordinates.
House.not_geocoded # To get objects with coordinates.
Geocoder makes it really easy to show nearby objects to a particular geocoded object. Say you have a House object, and within 10 km distance of that object, you would like to have other ojbects in an array. Good news is that there isn’t much to it – all you have to do is to call nearbys (it is an object method), pass the distance as an arugment (default unit is km) and you are going to get back objects that you can iterate through and do different stuff with:
<% @house.nearbys(10).each do |nearby_house| %>
<%= link_to nearyby_house.owner.name + "'s home", nea
<% end %>
Geocoder is a all-in-one package, providing you with all the things you are going to need for building a web application that uses geolocation a lot from basic mapping to complex calculations. We hope that it will meet your needs in your project and if there is anything that you would like to see added to this series of articles, kindly let us know in comments.