Last active
December 20, 2015 20:58
-
-
Save FabienArcellier/6193607 to your computer and use it in GitHub Desktop.
Algorithm of Haversine to calculate distance between two gps coord for MySQL
This file contains 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
DELIMITER // | |
CREATE FUNCTION `distance` (p1_latitude DOUBLE, p1_longitude DOUBLE, p2_latitude DOUBLE, p2_longitude DOUBLE) RETURNS DOUBLE | |
BEGIN | |
DECLARE deg2rad DOUBLE DEFAULT 0.0174; -- 3.14/180 or 2PI/360 | |
DECLARE distance_latitude, distance_longitude, a DOUBLE; | |
SET distance_latitude = ( p2_latitude - p1_latitude ) * deg2rad; | |
SET distance_longitude = ( p2_longitude - p1_longitude ) * deg2rad; | |
SET a = sin( distance_latitude * .5 ) * sin( distance_latitude * .5 ) + cos( p1_latitude * deg2rad ) * cos( p2_latitude * deg2rad ) * sin( distance_longitude / 2 ) * sin( distance_longitude / 2 ); | |
RETURN round( ( 2 * atan2( sqrt(a) , sqrt(1-a) ) ) * 6371000 , 3 ); -- 6371000 : curve rayon of earth ; | |
END | |
// | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment