Topic: "Find nearest store..."

Hello everyone -

  Does anyone know of a plugin or an easy way to take a Zip Code and calculate the closest entries from a database depending on the Entry's Zip code?  Sort of like a "Store Locator" type of thing you find on most stores that have websites, like Best Buy or something. (Hopefully this makes sense...)

I know that this method requires the use of an algorithm that uses longitude and latitude and all, but was hoping there was a simple way to do so since Rails tries to make everything easier, hehe.

Thanks in advanced!

Re: "Find nearest store..."

You'd have to have a data source that mapped the coordinates of each zip code.  Rails can't give you that data.  What Rails can do is subtract one logitude from another and one latitude from another to give you the distance between two points.  You'll need to get the data on your own though.

Re: "Find nearest store..."

I know that United States ZIP Code / Canadian Postal Code databases with latitude & longitude are available at http//www.zipcodeworld.com   

Any advice as to where I should create this algorithm?  When a request is made to find the "nearest store", should that calculation be done in a Controller?

Re: "Find nearest store..."

No, that calculation should all be in the model.

Your code should look a little like this:

controller:

StoresController < ActionController::Base
  def search_by_zipcode
    @stores = Store.near_zipcode(params[:zipcode])
  end
end

model:
Store < ActiveRecord::Base
  def self.near_zipcode(zip)
    find_by_sql("SELECT * from ...")
  end
end

For details on how to actually construct the mysql query to find things that are near other things you should read this thread:
http://forums.mysql.com/read.php?23,3868,87201

You do NOT want to retrieve your whole database full of records and try to run the calculation with Rails.  You want to get the database to do that work for you and have it provide you with a nice little organize set of data.

Re: "Find nearest store..."

Thank you for the advice!

I will tell you all how it turns out, once I get to that point.

Re: "Find nearest store..."

xilo32, here is what you're looking for.

http://geokit.rubyforge.org/

You first need to populate your database with locations. You can find the latitude and longitude component by geocoding an address with geokit, with will use an external geocoder such as Google's, Yahoo's or Geocoder.us/ca.

Then you are ready to query the database, with say, find all locations within 10 miles of this location. Use geokit again.

For others, georuby and spatial adapter might also be interesting, but only for those requiring more than just points(polygon, lines etc.).

Re: "Find nearest store..."

Hey! Good Looking out Wackimonki!

This Geocoder plug-in is actually going to work a lot better than what I had in mind.

Thanks again!

Re: "Find nearest store..."

I just found this:

http://googlemapsapi.blogspot.com/2006/ … d-get.html

sweet as !