Sunday, February 19, 2017

script to calculate distance among latitude and longitude points

import math
import sys
#https://en.wikipedia.org/wiki/Haversine_formula
#t = 0a2320486176657273696e652061203d2073696ec2b228ce94cf862f3229202b20636f7320cf863120e28b8520636f7320cf863220e28b852073696ec2b228ce94cebb2f32290a2320666f726d756c613a20202020200a232063203d203220e28b85206174616e322820e2889a612c20e2889a2831e28892612920290a232064203d205220e28b852063200a
# print t.decode('hex')

# global
def getDistance(co1, co2):
    R = 6371000
    lat1, lng1 =co1.split(",")
    lat2, lng2 =co2.split(",")
    lat1 = float(lat1)
    lng1 = float(lng1)
    lat2 = float(lat2)
    lng2 = float(lng2)
    rlat1 = math.radians(lat1)
    rlat2 = math.radians(lat2)
    llat = math.radians(lat2 - lat1)
    llng = math.radians(lng2 - lng1)

    a = math.sin(llat/2.0) * math.sin(llng/2.0)+ math.cos(rlat1) * math.cos(rlat2) * math.sin(llng/2.0) * math.sin(llat/2.0)
    c = 2 * math.atan2(math.sqrt(a),math.sqrt(1-a))
    d = R * c

    return
def getDistance2(co1, co2):
    R = 6371000
    lat1, lng1 =co1.split(",")
    lat2, lng2 =co2.split(",")
    lat1 = float(lat1)
    lng1 = float(lng1)
    lat2 = float(lat2)
    lng2 = float(lng2)
    rlat1 = math.radians(lat1)
    rlat2 = math.radians(lat2)
    rlng1 = math.radians(lng1)
    rlng2 = math.radians(lng2)
    llat = math.radians(lat2 - lat1)
    llng = math.radians(lng2 - lng1)


    d = 2 * R * math.asin(math.sqrt((math.sin((rlat2/2 - rlat1/2))) ** 2 + math.cos(rlat1) * math.cos(rlat2) *(math.sin((rlng2/2 - rlng1/2))) ** 2 ) )

    return d


d = 0
n = 0
cos = sys.argv[1:]
for i in cos:
    if len(sys.argv) - 2 <= n:
        break
    d += getDistance2(i,cos[n+1])
    n += 1


print str(d) + " m"
print str(d/1000) + " km"
# print getDistance2(p2,p1)




usage:
$ python distance.py 104.49861,11.49440 104.67526,11.49619 104.77782,11.39387
31407.8297532 m
31.4078297532 km


$ python distance.py 104.49861,11.49440 104.67526,11.49619
19642.6477521 m
19.6426477521 km


No comments:

Post a Comment