Skip to content

Instantly share code, notes, and snippets.

@tobyprivett
Created May 13, 2016 20:33
Show Gist options
  • Select an option

  • Save tobyprivett/878345eadac811d19ee5fa2f2cf3d6cf to your computer and use it in GitHub Desktop.

Select an option

Save tobyprivett/878345eadac811d19ee5fa2f2cf3d6cf to your computer and use it in GitHub Desktop.
// 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