Latitude and Longitude distance calculator
Python
# Import Modules
import math
# Set latitude and longitude using decimal numbers
lat1 = 49.90
lon1 = -97.14
lat2 = 41.88
lon2 = -87.62
# Create distance-measuring function
def haversine_distance(lat1, lon1, lat2, lon2):
# Convert latitude and longitude from degrees to radians
lat1_rad = math.radians(lat1)
lon1_rad = math.radians(lon1)
lat2_rad = math.radians(lat2)
lon2_rad = math.radians(lon2)
# Haversine formula
dlat = lat2_rad - lat1_rad
dlon = lon2_rad - lon1_rad
a = math.sin(dlat / 2) ** 2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
radius_earth_km = 6371.0 # Earth's radius in kilometers
distance_km = radius_earth_km * c
return distance_km
metricdist = haversine_distance(lat1, lon1, lat2, lon2)
imperialdist = (metricdist * 0.6214)
print("Distance between "+str(lat1)+" "+str(lon1)+" and "+str(lat2)+" "+str(lon2)+": "+str(metricdist)+" km or "+str(imperialdist)+ " mi.")
Output
Embed on website
To embed this program on your website, copy the following code and paste it into your website's HTML:
Comments
This comment belongs to a banned user and is only visible to admins.
This comment belongs to a deleted user and is only visible to admins.