ECSP




Pay Notebook Creator: Haige Cui0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0
In [1]:
from geopy import GoogleV3
geocode = GoogleV3('AIzaSyDNqc0tWzXHx_wIp1w75-XTcCk4BSphB5w').geocode 
user_address = '128-12 18th Ave'
x = geocode(user_address)
user_coor = x.longitude, x.latitude
user_coor
Out[1]:
(-73.8398519, 40.7830768)
In [4]:
type(user_coor)
Out[4]:
tuple
In [2]:
# test
import geopy
import geopy.distance

pt1 = geopy.Point(48.853, 2.349)
#pt2 = geopy.Point(52.516, 13.378)
#dist = geopy.distance.distance(pt1, pt2).miles
#type(pt1)
In [3]:
dist = geopy.distance.distance(pt1, user_coor).miles
dist
Out[3]:
8648.088267481859
In [2]:
# below codes work the same with above
# from geopy.distance import lonlat, distance
# newport_ri_xy = (-71.312796, 41.49008)
# cleveland_oh_xy = (-81.695391, 41.499498)
# print(distance(lonlat(*newport_ri_xy), lonlat(*cleveland_oh_xy)).miles)
538.3904453677203
In [16]:
positions = 
[(-73.913146,  40.716759),
       (-73.998209,  40.665231),(-81.695391, 41.499498)]
In [17]:
def calculate_distance(positions):
    results = []
    for i in range(1, len(positions)):
        loc1 = positions[i - 1]
        loc2 = positions[i]

        lat1 = loc1[0]
        lng1 = loc1[1]

        lat2 = loc2[0]
        lng2 = loc2[1]

        degreesToRadians = (math.pi / 180)
        latrad1 = lat1 * degreesToRadians
        latrad2 = lat2 * degreesToRadians
        dlat = (lat2 - lat1) * degreesToRadians
        dlng = (lng2 - lng1) * degreesToRadians

        a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(latrad1) * \
        math.cos(latrad2) * math.sin(dlng / 2) * math.sin(dlng / 2)
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
        r = 6371000

        results.append(r * c)

    return (sum(results) / 1000)
In [18]:
calculate_distance
Out[18]:
<function __main__.calculate_distance(positions)>
In [ ]: