Created
May 13, 2016 20:33
-
-
Save tobyprivett/878345eadac811d19ee5fa2f2cf3d6cf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // php implementation from http://stackoverflow.com/questions/14750275/haversine-formula-with-php | |
| I calculate distances straight inside queries, using the following stored procedure: | |
| CREATE FUNCTION GEODIST (lat1 DOUBLE, lon1 DOUBLE, lat2 DOUBLE, lon2 DOUBLE) | |
| RETURNS DOUBLE | |
| DETERMINISTIC | |
| BEGIN | |
| DECLARE dist DOUBLE; | |
| SET dist = round(acos(cos(radians(lat1))*cos(radians(lon1))*cos(radians(lat2))*cos(radians(lon2)) + cos(radians(lat1))*sin(radians(lon1))*cos(radians(lat2))*sin(radians(lon2)) + sin(radians(lat1))*sin(radians(lat2))) * 6378.8, 1); | |
| RETURN dist; | |
| END| | |
| You just execute the above as an SQl statement from within phpMyAdmin to create the procedure. Just notice the ending |, so in your SQL input window, choose for the | sign as limiter. | |
| Then in a query, call it like this: | |
| $sql = " | |
| SELECT `locations`.`name`, GEODIST(`locations`.`lat`, `locations`.`lon`, " . $lat_to_calculate . ", " . $lon_to_calculate . ") AS `distance` | |
| FROM `locations` "; | |
| I found this to be a lot faster than calculating it in PHP after the query has been run. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment