5

Options

$lat = '25.7742658';
$lng = '-80.1936589';
$miles = 30;

Query

SELECT *, 
   ( 3959 * acos( cos( radians($lat) ) 
   * cos( radians( lat ) ) 
   * cos( radians( lng ) - radians($lng) ) 
   + sin( radians($lat) ) 
   * sin( radians( lat ) ) ) ) AS distance 
FROM locations 
HAVING distance < $miles 
ORDER BY distance 
LIMIT 0, 20

I have a database table with 4 columns:

  • unique id
  • city name
  • latitude (lat)
  • longitude (lng)

I'm using the query on top to return locations that are within a specified number of miles from the specified coordinates. It seems to work but I'm not sure how accurate it is. I'm curios to know whether the query is good or if you have a better solution.

1 Answer 1

3

that looks like the correct great circle distance query.

what are you concerned with wrt accuracy?

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for confirming! I'm just concerned that there's a better solution. I read a little about MYSQL spatial extensions and I'm not sure whether I should implement that instead.
if this is what you are doing, then the extension is overkill. you should be good to go :)
The formula you are using is spherical law of cosines. Check it out from en.wikipedia.org/wiki/Spherical_law_of_cosines. Another formula for great circle distance is Haversine formula. Check it out from en.wikipedia.org/wiki/Haversine_formula. Both formulas assume a spherical earth. Law of cosines is faster to compute. You are on the right track.
else you should consider is that you want to handle distances to distances few miles the formula for spheres is good, for longer distances, you would be a more complicated formula, but the distance to use this right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.