Find users within the radius of location based on zip code

65 views Asked by At

I have an app/site and need to perform a search for all users located within a user specified distance of their zip code. I have two tables, one with user data and a second with zip code information. I'm having difficulties figure out the query to find users that are within the distance. I don't understand geospatial query needed to make it work.

User Table Structure

username        zip 
=====================   
tester55        60608   
Tester1         00544   
iosuser1        73120   
Tester3         01002

Zipcodes Table Structure

zip     latitude     longitude
------------------------------
00501   40.8154      -73.0451
00544   40.8154      -73.0451
01001   42.0702      -72.6227
01002   42.3671      -72.4646

I want to use the zip code of a user to find other users within a certain radius. Here are the queries I have so far, I'm trying to figure out how to make it one query.

First Query

    Select users.zip, users.username, zipcodes.zip as user zip, 
zipcodes.longitude as userlong, zipcodes.latitude as userlat
from users, zipcodes where users.zip = zipcodes.zip AND username = 'tester55

Second Query

SELECT zipcodes.zip, zipcodes.city, zipcodes.state, zipcodes.longitude, zipcodes.latitude, ( 3959 * acos( cos( radians(userlat) ) * cos( radians( zipcodes.latitude ) ) 
    * cos( radians( zipcodes.longitude ) - radians(userlong) ) + sin( radians(userlat) ) * sin(radians(zipcodes.latitude)) ) ) AS distance 
FROM zipcodes
HAVING distance < 50
ORDER BY distance

Any help is greatly appreciated.

0

There are 0 answers