Created
July 4, 2012 04:39
-
-
Save overthemike/3045366 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
CREATE PROCEDURE geodist (IN userid int, IN dist int) | |
BEGIN | |
declare mylon double; | |
declare mylat double; | |
declare lon1 float; | |
declare lon2 float; | |
declare lat1 float; | |
declare lat2 float; | |
-- get the original lon and lat for the userid: | |
select longitude, latitude into mylon, mylat from users where id=userid limit 1; | |
-- calculate lon and lat for the rectangle (~69 miles per one degree): | |
set lon1 = mylon - dist / abs(cos(radians(mylat))*69); | |
set lon2 = mylon + dist / abs(cos(radians(mylat))*69); | |
set lat1 = mylat - (dist / 69); | |
set lat2 = mylat + (dist / 69); | |
-- run the query | |
select | |
destination.*, | |
-- lots of Math here...just trust it - it works - I tested it... | |
3956 * 2 * ASIN(SQRT(POWER(SIN((orig.lat-dest.lat)*pi()/180/2),2)+COS(orig.lat*pi()/180)*COS(dest.lat*pi()/180)*POWER(SIN((orig.lon-dest.lon)*pi()/180/2),2))) as distance | |
from | |
users destination, users origin | |
where | |
origin.id = userid | |
and destination.longitude between lon1 and lon2 | |
and destination.latitude between lat1 and lat2 | |
having distance < dist | |
order by distance limit 10; | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment