Skip to content

Commit

Permalink
class and methods to compute the distance between two lat/lon pairs.
Browse files Browse the repository at this point in the history
  • Loading branch information
pcelico00 committed May 17, 2016
1 parent c68a1e0 commit 4584b21
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 44 additions & 0 deletions src/haversine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
Created on May 18, 2016
@author: Paul Celicourt
@email: [email protected]
"""

import math


class Haversine(object):
def __init__(self):
self.earth_radius = 6373 # km

def convert_degree_to_radian(self, value_in_degree):
value_in_radian = math.radians(value_in_degree)
return value_in_radian

def compute_distance_between_lat_lon_pairs(self, origin_lat_lon_pair, destination_lat_lon_pair):

origin_latitude, origin_longitude = origin_lat_lon_pair
destination_latitude, destination_longitude = destination_lat_lon_pair

assert (-180 <= origin_longitude <= 180)
assert (-180 <= destination_longitude <= 180)
assert (-90 <= origin_latitude <= 90)
assert (-90 <= destination_latitude <= 90)

origin_latitude_in_radian = math.radians(origin_latitude)
origin_longitude_in_radian = math.radians(origin_longitude)
destination_latitude_in_radian = math.radians(destination_latitude)
destination_longitude_in_radian = math.radians(destination_longitude)

latitude_difference_in_radian = destination_latitude_in_radian - origin_latitude_in_radian
longitude_difference_in_radian = destination_longitude_in_radian - origin_longitude_in_radian

haversine_of_central_angle = (math.sin(latitude_difference_in_radian/2))**2 + \
math.cos(destination_latitude_in_radian) * math.cos(origin_latitude_in_radian) * \
(math.sin(longitude_difference_in_radian/2))**2

central_angle = 2 * math.atan2(math.sqrt(haversine_of_central_angle), math.sqrt(1-haversine_of_central_angle))
distance_between_lat_lon_pairs = self.earth_radius * central_angle

return distance_between_lat_lon_pairs
22 changes: 22 additions & 0 deletions src/testshaversine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
Created on May 18, 2016
@author: Paul Celicourt
@email: [email protected]
"""

import unittest

from haversine import Haversine

class HaversineSuperTest(unittest.TestCase):

def setUp(self):
self.harversine_object = Haversine()


class HaversineTest(HaversineSuperTest):
def test_compute_distance_between_lat_lon_pairs(self):
distance = self.harversine_object.compute_distance_between_lat_lon_pairs((52.2296756,21.0122287),
(52.406374,16.9251681))
self.assertAlmostEqual(distance, 278.545589351, 3)

0 comments on commit 4584b21

Please sign in to comment.