Last active
August 29, 2015 14:01
-
-
Save jbouzekri/9d2c73301babdbb867c9 to your computer and use it in GitHub Desktop.
get_distance_meters function : get distance in 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 // | |
/* | |
Exemple : | |
You have table city with latitude and longitude column. | |
get_distance_meters(my_latitude, my_longitude, city.latitude, city.longitude) | |
return the distance in km | |
*/ | |
CREATE FUNCTION get_distance_meters ( lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT ) RETURNS DOUBLE PRECISION | |
BEGIN | |
DECLARE pi, q1, q2, q3 DOUBLE PRECISION; | |
DECLARE rads DOUBLE PRECISION DEFAULT 0; | |
SET pi = PI(); | |
SET lat1 = lat1 * pi / 180; | |
SET lon1 = lon1 * pi / 180; | |
SET lat2 = lat2 * pi / 180; | |
SET lon2 = lon2 * pi / 180; | |
SET q1 = COS(lon1-lon2); | |
SET q2 = COS(lat1-lat2); | |
SET q3 = COS(lat1+lat2); | |
SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ); | |
RETURN 6378.388 * rads; | |
END// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment