If you have a latitude and longitude stored in your database and need to calculate the distance between two coordinates. How can you calculate it using a MySQL function?
from math import cos, asin, sqrt, pi def distance(lat1, lon1, lat2, lon2): p = pi/180 a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2 return 12742 * asin(sqrt(a)) #2*R*asin... And for the sake of completeness: Haversine on Wikipedia.
Euclidean Distance = SquareRoot(((x2-x1)^2)+((y2-y1)^2)) SquareRoot can be written as (something)^(0.5) I implemented like that. CAST(ROUND(LONG_W ,4) as numeric(36,4)) is for taking value upto 4 decimal point.
After searching around for awhile, I gave up and wrote it myself. I was able to adapt some other code to the following MySQL function.
DELIMITER $$
/*
Takes two latitudes and longitudes in degrees. You could comment out the conversion if you want to pass as radians.
Calculate the distance in miles, change the radius to the earth's radius in km to get km.
*/
DROP FUNCTION IF EXISTS GETDISTANCE$$
CREATE FUNCTION GETDISTANCE
(deg_lat1 FLOAT, deg_lng1 FLOAT, deg_lat2 FLOAT, deg_lng2 FLOAT)
RETURNS FLOAT
DETERMINISTIC
BEGIN
DECLARE distance FLOAT;
DECLARE delta_lat FLOAT;
DECLARE delta_lng FLOAT;
DECLARE lat1 FLOAT;
DECLARE lat2 FLOAT;
DECLARE a FLOAT;
SET distance = 0;
/*Convert degrees to radians and get the variables I need.*/
SET delta_lat = radians(deg_lat2 - deg_lat1);
SET delta_lng = radians(deg_lng2 - deg_lng1);
SET lat1 = radians(deg_lat1);
SET lat2 = radians(deg_lat2);
/*Formula found here: http://www.movable-type.co.uk/scripts/latlong.html*/
SET a = sin(delta_lat/2.0) * sin(delta_lat/2.0) + sin(delta_lng/2.0) * sin(delta_lng/2.0) * cos(lat1) * cos(lat2);
SET distance = 3956.6 * 2 * atan2(sqrt(a), sqrt(1-a));
RETURN distance;
END$$
DELIMITER ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With