Created distance calculation.
This commit is contained in:
31
main/distance.py
Normal file
31
main/distance.py
Normal file
@@ -0,0 +1,31 @@
|
||||
#! /usr/bin/env
|
||||
|
||||
from math import radians, cos, sin, asin, sqrt
|
||||
|
||||
# helper to calculate geographical distance using lat, lon
|
||||
def get_distance(p1: tuple, p2: tuple):
|
||||
'''
|
||||
Returns a float that is the distance, in miles, between two (lat,lon) tuples.
|
||||
Parameters:
|
||||
p1 (tuple): point 1
|
||||
p2 (tuple): point 2
|
||||
Returns:
|
||||
distance (float): miles between points
|
||||
'''
|
||||
# The math module contains a function named
|
||||
# radians which converts from degrees to radians.
|
||||
p1 = (radians(p1[0]),radians(p1[1]))
|
||||
p2 = (radians(p2[0]),radians(p2[1]))
|
||||
|
||||
# Haversine formula
|
||||
dlon = p2[1] - p1[1]
|
||||
dlat = p2[0] - p1[0]
|
||||
a = sin(dlat / 2)**2 + cos(p1[0]) * cos(p2[0]) * sin(dlon / 2)**2
|
||||
|
||||
c = 2 * asin(sqrt(a))
|
||||
|
||||
# Radius of earth in kilometers. Use 3956 for miles
|
||||
r = 3956
|
||||
|
||||
# calculate the result
|
||||
return(c * r)
|
||||
Reference in New Issue
Block a user