Skip to content

Instantly share code, notes, and snippets.

@FabienArcellier
Last active December 20, 2015 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FabienArcellier/6193607 to your computer and use it in GitHub Desktop.
Save FabienArcellier/6193607 to your computer and use it in GitHub Desktop.
Algorithm of Haversine to calculate distance between two gps coord for MySQL
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