Created
November 12, 2009 22:15
-
-
Save ruckus/233355 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# t.column "latitude", :decimal, :precision => 10, :scale => 4, :default => 0.0, :null => false | |
# t.column "longitude", :decimal, :precision => 10, :scale => 4, :default => 0.0, :null => false | |
# def want index on both | |
def find_nearby(radius = 10, limit = 10) | |
distance_sql = <<-SQL_END | |
IFNULL(SQRT( ((69.1 * (#{self.latitude} - zips.latitude)) * (69.1 * (#{self.latitude} - zips.latitude))) | |
+ ( (53 * (#{self.longitude} - zips.longitude)) * (53 * (#{self.longitude} - zips.longitude)))),0) | |
SQL_END | |
zips = Zip.find( :all, | |
:select => "*, #{distance_sql} as distance", | |
:limit => limit, | |
:order => "distance ASC", | |
:conditions => [" | |
zips.longitude >= (#{self.longitude} - (#{radius}/(COS(#{self.latitude})))) | |
AND zips.longitude <= (#{self.longitude} + (#{radius}/(COS(#{self.latitude})))) | |
AND zips.latitude >= (#{self.latitude} - (0.0143884892 * #{radius})) | |
AND zips.latitude <= (#{self.latitude} + (0.0143884892 * #{radius}))"]) | |
if zips.length > 0 | |
return zips | |
else | |
return [self] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment