brybam
brybam

Reputation: 5019

How to Query Mysql based on GPS latitude and longitude columns based on relative distance

In an app I'm building, One of the features i'd like users to be able to discover people around them easily. I'm using the GPS to get the latitude and longitude, then storing that information in the mysql db along with the other user information under a column for latitude and another with the longitude. What's would the best practice be to do a query that looks at the person whos making the query's information...and then have it find the closest possible relatable lat and longitude then start there and limit it to 24 results? And furthermore, how would I remember where it stopped so I could allow another query to start where it left off and return more getting further and further away

Basically, to generalize how can I do a mysql query that starts as close as it can to 2 latitude and longitude points that I supply and then have it grab the next 24 sorted by closest to furthest?

I feel like its going to be hard to do because its being based on 2 columns. Is there a way I should/could be combining the GPS values into 1 column so it will be easy to find relative distance?

Maybe I could somehow get the zip code (but then that might cause non US problems). I'm not sure. I'm stuck.

Upvotes: 2

Views: 3302

Answers (2)

ldg
ldg

Reputation: 9402

As @cdonner mentioned, there are a number of resources for the Haversine formula which you use to transform lat and long into distance. You would pass in a distance variable based on how your formula is set up, usually based on miles and run your query starting at the closest radius. Using a php loop, you can simply increase the distance and re-run the query until you get the desired number of results. And do check out that google link re @Maleck13 as well, very helpful.

Upvotes: 0

cdonner
cdonner

Reputation: 37658

Just search for "Haversine Formula" here on Stackoverflow and you will find several related questions.

Upvotes: 2

Related Questions