Created
August 13, 2014 12:04
-
-
Save r8n5n/0f1300a13fc6473b6519 to your computer and use it in GitHub Desktop.
MySQL Function to get distance between 2 locations (lat,lon) in KM
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
DELIMITER $$ | |
DROP FUNCTION IF EXISTS d $$ | |
CREATE FUNCTION d(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT | |
DETERMINISTIC | |
BEGIN | |
DECLARE R FLOAT; | |
DECLARE rad FLOAT; | |
DECLARE a FLOAT; | |
DECLARE d FLOAT; | |
SET R = 6378137; | |
SET rad = 3.14159265359 / 180; | |
SET lat1 = lat1 * rad; | |
SET lat2 = lat2 * rad; | |
SET a = SIN(lat1) * SIN(lat2) + COS(lat1) * COS(lat2) * COS((lon2 - lon1) * rad); | |
SET d = ROUND((R * ACOS(LEAST(a, 1)))/1000); | |
RETURN d; | |
END$$ | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on Leaflet.js distance function https://github.com/Leaflet/Leaflet/blob/master/src/geo/crs/CRS.Earth.js