Skip to content

Instantly share code, notes, and snippets.

@r8n5n
Created August 13, 2014 12:04
Show Gist options
  • Save r8n5n/0f1300a13fc6473b6519 to your computer and use it in GitHub Desktop.
Save r8n5n/0f1300a13fc6473b6519 to your computer and use it in GitHub Desktop.
MySQL Function to get distance between 2 locations (lat,lon) in KM
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 ;
@r8n5n
Copy link
Author

r8n5n commented Aug 13, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment