Loading page, please wait ...


Calculated Distance Using Haversine Formula

Select Origin In The Map



Result:



from js import document, alert #imported this to create a proxy function that will not execute when the page is loaded from pyodide import create_proxy #imported to do maths calculation for curvature from math import radians, cos, sin, asin, sqrt def button_click(event): FirstLat = document.getElementById("FirstLat").value FirstLong= document.getElementById('FirstLong').value SecLat= document.getElementById('SecLat').value SecLong= document.getElementById('SecLong').value # attempt conversion of input and alert if any of them # aren't valid conversions try: first_lat = float(FirstLat) first_long = float(FirstLong) sec_lat = float(SecLat) sec_long = float(SecLong) except ValueError: alert("Invalid inputs, please make sure you have valid coordinates input.") return False dx = sec_lat - first_lat dy = sec_long - first_long dsquared = dx*dx + dy*dy calculated_distance = dsquared**0.5 # to calculate with curvature using Haversine Formula first_lat_rad = radians(first_lat) sec_lat_rad = radians(sec_lat) first_long_rad = radians(first_long) sec_long_rad = radians(sec_long) # Calculating using the Haversine formula dlon = sec_long_rad - first_long_rad dlat = sec_lat_rad - first_lat_rad a = sin(dlat / 2)**2 + cos(first_lat_rad) * cos(sec_lat_rad) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) # We define the radius of the earth in miles r = 6371 # calculate the result calculated_distance = c * r #display the result document.getElementById("Distance").innerHTML = 'Calculated Distance: ' + str(calculated_distance) def setup(): # The page is ready, clear the "page loading" document.getElementById("msg").style.display = "none"; document.getElementById("container").style.visibility = "visible"; # Create a JsProxy for the callback function click_proxy = create_proxy(button_click) # Set the listener to the callback e = document.getElementById("button") e.addEventListener("click", click_proxy) setup()

To calculate the distance based on a network of roads with a UI please click the following link!

Distance Calculator Based on a network of roads called from an API with User Interface