6

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?

jpgunter
  • 502
  • 4
  • 10
  • It is permissible to answer your own question, but you you need ask a question. You also need to explain what assumptions you're making. For example, you are likely expressing the distance in miles rather than, say, kilometres. It looks like your coordinates are expressed in degrees. Your function documentation should say so. You are also assuming a spherical earth rather than a spheroidal earth. – Jonathan Leffler Dec 05 '12 at 04:34
  • 2
    @SashiKant I edited the post to be a question that I answer. – jpgunter Dec 05 '12 at 04:48
  • @JonathanLeffler I changed it to be a question with my answer and added the documentation. – jpgunter Dec 05 '12 at 04:48

1 Answers1

11

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 ;
jpgunter
  • 502
  • 4
  • 10