Great Circle Distance

Developed In: SQL — Contributed by: bramsi

Calculate/measure distance between two poins using Great Circle Distance algorithm.

Code translate from geopy http://code.google.com/p/geopy/.


bramsi
SQL
  1. DELIMITER ;;
  2. DROP FUNCTION IF EXISTS `gcd2`;;
  3.  
  4. CREATE FUNCTION `gcd2`(longitude0 DOUBLE, latitude0 DOUBLE, longitude1 DOUBLE, latitude1 DOUBLE, metric VARCHAR(2)) RETURNS DOUBLE
  5. DETERMINISTIC
  6. COMMENT 'Great Circle Distance http://code.google.com/p/geopy/'
  7. BEGIN
  8. DECLARE gcdx DOUBLE;
  9. DECLARE lng_rad0 DOUBLE;
  10. DECLARE lat_rad0 DOUBLE;
  11. DECLARE lng_rad1 DOUBLE;
  12. DECLARE lat_rad1 DOUBLE;
  13. DECLARE sin_lat0 DOUBLE;
  14. DECLARE cos_lat0 DOUBLE;
  15. DECLARE sin_lat1 DOUBLE;
  16. DECLARE cos_lat1 DOUBLE;
  17. DECLARE delta_lng DOUBLE;
  18. DECLARE cos_delta_lng DOUBLE;
  19. DECLARE sin_delta_lng DOUBLE;
  20. DECLARE central_angle DOUBLE;
  21.  
  22. DECLARE earth_radius DOUBLE;
  23.  
  24. SET earth_radius := 6372.795;
  25.  
  26. SET lng_rad0 := RADIANS(longitude0);
  27. SET lat_rad0 := RADIANS(latitude0);
  28. SET lng_rad1 := RADIANS(longitude1);
  29. SET lat_rad1 := RADIANS(latitude1);
  30.  
  31. SET sin_lat0 := SIN(lat_rad0);
  32. SET cos_lat0 := COS(lat_rad0);
  33. SET sin_lat1 := SIN(lat_rad1);
  34. SET cos_lat1 := COS(lat_rad1);
  35.  
  36. SET delta_lng := lng_rad1 - lng_rad0;
  37. SET cos_delta_lng := COS(delta_lng);
  38. SET sin_delta_lng := SIN(delta_lng);
  39.  
  40. SET central_angle := acos(sin_lat0 * sin_lat1 + cos_lat0 * cos_lat1 * cos_delta_lng);
  41.  
  42. SET gcdx := atan2(sqrt(POW((cos_lat1 * sin_delta_lng), 2) + POW((cos_lat0 * sin_lat1 - sin_lat0 * cos_lat1 * cos_delta_lng), 2)), sin_lat0 * sin_lat1 + cos_lat0 * cos_lat1 * cos_delta_lng);
  43.  
  44. IF metric = 'km' THEN
  45. RETURN gcdx * earth_radius;
  46. ELSEIF metric = 'mi' THEN
  47. RETURN (gcdx * earth_radius) * 0.621371192;
  48. ELSEIF metric = 'nm' THEN
  49. RETURN (gcdx * earth_radius) / 1.852;
  50. ELSE
  51. RETURN gcdx;
  52. END IF;
  53. END;;
  54.  
  55. DELIMITER ;

Current Tags

You must be logged in to tag this tool

No Comments yet

Votes

Not yet rated.
You must be logged in to vote.

Watches

0 members are watching this tool
You must be logged in to track this tool.

Provide Feedback

Please note:
HTML will be purified, but we allow for a number of HTML tags so that you have the flexibility to decorate your comment text to some extent. The comments allow the following HTML tags:

strong, b, em, blockquote, a, code, pre

To put code into your comment, simply encapsulate your code with
[code language="XXX"][/code], where XXX is any common language, for instance "PHP", "SQL", "C", etc.



You must be logged in to comment