Ruby on rails yahoo-geocoder
I recently was given a task which required some geocoding. Eventually the geocodes will find there way into a google map. The temptation with google maps is the geocode everything using googles built in geocoding. This is great for a couple of points. However if you are going to have many points you are better off caching the longitude and latitude for speedy marker sets.
in order to get yahoo-geocoder working you’ll want to install the gem
Gem install yahoo-geocode
After that simple step you will want to reboot any mongrel or webrick servers that are running to ensure that the new gem is loaded in your environment.
once installed you need to get a key from yahoo
you should be ready to go now. using the yahoo geocode api to cache latitude and longitude is as simple as this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | require 'yahoo/geocode' class Post < ActiveRecord::Base before_validation :fillfields validates_presence_of :latitude validates_presence_of :zipcode, :if=>:in_us? validates_presence_of :city def in_us? country=='US' end private def fillfields yg=Yahoo::Geocode.new "Your api id goes here" begin locations = yg.locate self.zipcode+', '+self.city+', '+self.country self.longitude=locations.first.longitude self.latitude =locations.first.latitude self.city = locations.first.city self.country = locations.first.country rescue self.errors.add_to_base('Validation could not be done') end end end |
As you can see everything is nicely tucked away in the posts model. There are no changes to the views or controllers for this one. After that you can call:
Post.find(:all).to_json
or
Post.find(:all).to_xml
to start consuming the locations in google maps or any other mapping software for that matter.
