Get results from mysql based on latitude longitude

Posted on

Get results from mysql based on latitude longitude – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and mysql . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about Get results from mysql based on latitude longitude.

I have a mysql Database and 2 tables let’s say clients and schools. Now each table has columns latitude and longitude. And I need do make a SELECT for example from second table where schools are in a given radius of one record from first table. Calculations should be made based on latitude and longitude.
PS: I am using PHP.

Solution :

You can calculate a distance using a Spherical law of cosines:

SELECT DEGREES(ACOS(SIN(RADIANS(clients.latitude)) * SIN(RADIANS(schools.latitude)) + 
                    COS(RADIANS(clients.latitude)) * COS(RADIANS(schools.latitude)) 
                                                   * COS(RADIANS(clients.longitude 
                                                               – schools.longitude)))) 
       * 60 * 1.1515 * 1.609344 AS distance
FROM clients, schools HAVING distance < $radius

RADIANS(X) – degrees to radians
ACOS(X) – the arc cosine of X, that is, the value whose cosine is X
DEGREES(X) – radians to degrees

60 – minutes in a degree
1.1515 – miles in a nautical mile
1.609344 – kilometres in a mile

Leave a Reply

Your email address will not be published. Required fields are marked *