Google Maps, Rails & GeoKit

written by justin on July 23rd, 2007 @ 04:29 PM

So recently (last week), I decided to integrate Google Maps into our site to show property locations. I had done some of this before on my very first Rails Project, so I had an idea of what I needed to do. I knew that I'd need a piece for doing the GeoCoding as this is how the API works on for Google Maps. I did a search on rails and Google Maps and found this little gem: GeoKit.

GeoKit is a Rails plugin that does a lot of cool stuff for you, and one of them is GeoCoding. I'm generally not a huge plugin guy, but I decided to give it a whirl anyway. I installed the plugin, read through the readme document and then proceeded to get my API keys from Yahoo and Google. The Yahoo key was strictly for their GeoCode service and the Google Key was for both GeoCoding and the Maps. There are a couple of other geocode services available in the plugin, but I thought that those 2 were sufficient.

GeoKit abstracts the GeoCoding away from you and even handles failover in case a service is not responding. I needed to add a couple of columns to my Property database table for latitude and longitude. After that was done, I wrote a quick method to populate my Property Model with GeoCode information.

  def populate_all_geocodes
    @locs = []
    
    @properties = Property.find(:all)
    @properties.each do |p|
      location = MultiGeocoder.geocode(p.full_address)
      if location.success
        @locs << location
        p.lat = location.lat
        p.lng = location.lng
        p.save
      end
    end
  end

After the lat and lng fields were all populated I made my google maps integrated page. Cool, it worked. I even made a custom marker that looks like a building (I hope it does anyway).

While I was building this stuff I noticed that there was a find by distance method in this plugin that allows you to search your table objects by distance from a location. So, this is possible: find all properties within X (miles|km) of GeoCode point. So, armed with this knowlege I built a zip code finder. You put in your zip code and the number of mile radius that you want to search and it returns all properties in that distance with the distance from your current zip code. You can have a look at the functioning product at nwrecc.org. I have to say that it works well and is really simple to use. See the project for other cool features of this plugin.

res = MultiGeocoder.geocode(params[:zip])
@props = Property.find(:all, 
                               :origin => [res.lat,res.lng], 
                               :conditions => ["distance < ?", params[:distance]], 
                               :order => 'distance')

Comments

  • Wing on 19 Feb 19:58

    hey I was just looking to make something like this for one of our clients. I'll be trying this out soon. Thanks!

Post a comment