Guest User

Untitled

a guest
May 26th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # found this somewhere pasted but can't recall.
  3. # bare-minimum requirement to do geo stuff with python when you can't benefit from
  4. # the numerous and powerful libs that normally do this.
  5.  
  6. import math
  7.  
  8. def haversine_distance(p1, p2):
  9. # points are lat, lon
  10. # and degrees
  11.  
  12. sin = math.sin
  13. cos = math.cos
  14.  
  15. lat1, lon1 = p1
  16. lat2, lon2 = p2
  17.  
  18. lat1 = lat1 / 180 * math.pi
  19. lat2 = lat2 / 180 * math.pi
  20. lon1 = lon1 / 180 * math.pi
  21. lon2 = lon2 / 180 * math.pi
  22.  
  23. dlat = lat2 - lat1
  24. dlon = lon2 - lon1
  25.  
  26. sin_dlat = sin(dlat / 2)
  27. sin_dlon = sin(dlon / 2)
  28.  
  29. return 2.0 * math.asin(math.sqrt(sin_dlat * sin_dlat + cos(lat1) * cos(lat2) * sin_dlon * sin_dlon))
  30.  
  31. def sphere_cos_distance(p1, p2):
  32. # points are lat, lon
  33. # and degrees
  34.  
  35. sin = math.sin
  36. cos = math.cos
  37.  
  38. lat1, lon1 = p1
  39. lat2, lon2 = p2
  40.  
  41. lat1 = lat1 / 180 * math.pi
  42. lat2 = lat2 / 180 * math.pi
  43. lon1 = lon1 / 180 * math.pi
  44. lon2 = lon2 / 180 * math.pi
  45.  
  46. dlon = lon2 - lon1
  47.  
  48. return math.acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(dlon))
  49.  
  50. def linear_distance(p1, p2):
  51. sin = math.sin
  52. cos = math.cos
  53.  
  54. lat1, lon1 = p1
  55. lat2, lon2 = p2
  56.  
  57. lat1 = lat1 / 180 * math.pi
  58. lat2 = lat2 / 180 * math.pi
  59. lon1 = lon1 / 180 * math.pi
  60. lon2 = lon2 / 180 * math.pi
  61.  
  62. average_lat = (lat1 + lat2) / 2
  63.  
  64. dlat = lat2 - lat1
  65. dlon = lon2 - lon1
  66.  
  67. scaled_dlon = dlon * cos(average_lat)
  68.  
  69. return math.sqrt(dlat * dlat + scaled_dlon * scaled_dlon)
  70.  
  71. def test_points(p1, p2):
  72. ha_dist = haversine_distance(p1, p2)
  73. # cos_dist = sphere_cos_distance(p1, p2)
  74. cos_dist = linear_distance(p1, p2)
  75.  
  76. print "%s %s %s %s" % (ha_dist, cos_dist, ha_dist / (ha_dist - cos_dist), ha_dist * 6375000)
  77.  
  78. def main():
  79. p1 = (37.5, 122.5)
  80. p2 = (37.5, 122.5 + 1e-5)
  81. p3 = (37.5, 122.5 + 1e-4)
  82. p4 = (37.5 + 1e-5, 122.5 - 1e-5)
  83. test_points(p1, p2)
  84. test_points(p1, p3)
  85. test_points(p1, p4)
  86.  
  87. if __name__ == "__main__":
  88. main()
Add Comment
Please, Sign In to add comment