2

I am trying to use this function found online to calculate the distance between two latitude and longitude points on the Earth.

However, I do not know how to pass my values for latitude and longitude because I replace lat1, lon1 and lat2, lon2, and I get an error every time.

Where do i put in the values I want for latitude and longitude?

import math

def distance(origin, destination):
    lat1, lon1 = origin
    lat2, lon2 = destination
    radius = 6371 # km

    dlat = math.radians(lat2-lat1)
    dlon = math.radians(lon2-lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = radius * c

    return d

EDIT: For example, if I have

lat1 = 20 and lon1 = 100 
lat2 = 30 and lon2 = 110 

why does it fail when I replace lon1 with the number in the function?

2 Answers 2

3

Use it like this:

distance((lat1, lon1), (lat2, lon2))

Notice that the function receives as parameters two two-element tuples (or two two-element lists, it'd be the same), each one representing a (latitude, longitude) pair. Equivalently:

origin = (lat1, lon1)
destination = (lat2, lon2)
distance(origin, destination)
Sign up to request clarification or add additional context in comments.

7 Comments

Im still confused as how to use this as I keep getting error when I try to execute. Say my lat1 = 20 and my lon1 = 100 and lat2 = 30 and lon2 = 110 how would I then put those numbers into your equation and the whole function. Thanks
Like this: distance((20, 100), (30, 200))
Lopez please can you edit the intial code above because Im trying yours and it wont work at all because i keep getting invalid syntax when i type in the tuples as you have shown
It works for me, exactly as I wrote above. You must be doing something else wrong, but my answer is correct, I even tested it with the example, it returns 9818.324994648268.
Thanks all i have it working now it was indeed a whitespace error Oscar :)
|
0

You could call it with named parameters by passing tuples for each one, like:

distance(origin=origin_tuple, destination=dest_tuple)

Where

origin_tuple = (origin_lat , origin_long)
dest_tuple = (dest_lat , dest_long)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.