Write a Python program to calculate distance between two points using latitude and longitude


Calculates the distance between two points on the Earth's surface using the Haversine formula. It takes latitude and longitude coordinates for a starting point and an ending point as input and calculates the distance between them in kilometers

  • It imports the necessary trigonometric functions (radians, sin, cos, acos) from the math module.
  • It prompts the user to enter the latitude and longitude coordinates for the starting and ending points. The coordinates are entered in degrees and then converted to radians using the radians function.
  • The Haversine formula is used to calculate the distance between the two points. The formula is:
  •     d = 6371.01 * acos(sin(slat) * sin(elat) + cos(slat) * cos(elat) * cos(slon - elon))

    • slat and slon are the latitude and longitude of the starting point in radians.
    • elat and elon are the latitude and longitude of the ending point in radians.
    • d is the calculated distance in kilometers.
  • Finally, it prints the calculated distance in kilometers with two decimal places

Source Code

from math import radians, sin, cos, acos
 
#latitude and longitude coordinates for the starting point
slat = radians(float(input("Enter the Starting Latitude : ")))
slon = radians(float(input("Enter the Starting Longitude : ")))
 
#latitude and longitude coordinates for the ending point
elat = radians(float(input("Enter the Ending Latitude : ")))
elon = radians(float(input("Enter the Ending Longitude : ")))
 
# Calculate the distance using the Haversine formula
d = 6371.01 * acos(sin(slat) * sin(elat) + cos(slat) * cos(elat) * cos(slon - elon))
 
 
print("The distance is %.2f km" % d)

Output

Starting latitude = 37.7749
Starting longitude = -122.4194
Ending latitude = 34.0522
Ending longitude = -118.2437
Distance = 559.12 km

Example Programs