Created
May 5, 2014 09:17
-
-
Save anytizer/11532222 to your computer and use it in GitHub Desktop.
Distance calculator
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
-- http://www.sqlexamples.info/SPAT/mysql_distance.htm | |
DROP FUNCTION IF EXISTS fn_distance; | |
DELIMITER $$ | |
CREATE FUNCTION fn_distance( | |
p_x1 FLOAT, p_y1 FLOAT, | |
p_x2 FLOAT, p_y2 FLOAT | |
) | |
RETURNS FLOAT | |
DETERMINISTIC | |
BEGIN | |
DECLARE v_dist FLOAT; | |
DECLARE A FLOAT; DECLARE B FLOAT; | |
DECLARE C FLOAT; DECLARE D FLOAT; | |
/** | |
* Returns distance calculation between two points in LAT-LONG coordinates | |
*/ | |
SET v_dist = 0; | |
-- Convert to radians | |
SET A = p_x1 / 57.29577951; | |
SET B = p_y1 / 57.29577951; | |
SET C = p_x2 / 57.29577951; | |
SET D = p_y2 / 57.29577951; | |
IF (A = C && B = D) THEN | |
SET v_dist = 0; | |
ELSEIF ((SIN(A)*SIN(C)+COS(A)*COS(C)*COS(B - D)) > 1) THEN | |
SET v_dist = 3963.1 * ACOS(1); | |
ELSE | |
SET v_dist = 3963.1*ACOS(SIN(A)*SIN(C) + COS(A)*COS(C)*COS(B - D)); | |
END IF; | |
/* Return distance in km. */ | |
SET v_dist = v_dist * 1.609; | |
RETURN v_dist; | |
END $$ | |
/* Distance from Duomo to Castello Sforzesco */ | |
SELECT fn_distance (9.1918377,45.4642822,9.1794726,45.4702864) AS dist_km; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment