Geocoder is a complete Geocoding solution for Ruby. With Rails, it adds Geocoding (by street or IP address), Reverse Geocoding (find street address based on given coordinates), and Distance Queries. It’s as simple as calling Geocode on your objects, and then using a scope.
The Geocode method sends a request to an external API, by default the Google Maps API. As it calls an external service it would be better to move this call into a background process.
Install Geoceder Gem
$ gem install geocoder
Simple Usage for Gem Geocoder
- Create New Apps.
- Add gem geocoder in Gemfile.
- Add method from geocoder in your model.
Example
geocoded_by :address
Add Reverse method
reverse_geocoded_by :latitude, longitude
Add Callback
after_validations :geocode
Distance Location
You can add code for search distance between two location, example:
@location_first = Location.create(address: “Bandung, Jawa Barat”) @location_second = Location.create(address: “Cimahi, Jawa Barat”)
Then
@location_first.distance_to(@location_second)
Pretty Form for Search Location
For this field, I add jQuery for pretty search or Geocomplete.
Add library jQuery from Google Maps API, Ajax to your source and file jQuery Geocomplete
<script src='http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places' ></script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ></script>
<%= javascript_include_tag "jquery.geocomplete" %>
Then you can use this jQuery syntax:
var options = {
map: ".map_canvas"
};
$("#geocomplete").geocomplete(options);
Hope this article helpful for you.
Written by M. Luay – Developer at 41studio
Read more at the source