Georouted Distance Calculator



Click the map to begin!

from pyodide.http import pyfetch from js import document, alert from pyodide import create_proxy import asyncio from math import radians, cos, sin, asin, sqrt def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance in kilometers between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers return c * r async def button_click(event): FirstLat = document.getElementById("FirstLat").value FirstLong = document.getElementById('FirstLong').value SecLat = document.getElementById('SecLat').value SecLong = document.getElementById('SecLong').value route = [] headers = { 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8', } response = await pyfetch(url=f"https://api.openrouteservice.org/v2/directions/driving-car?api_key=5b3ce3597851110001cf62487621a9df4b6a49cdbc6f26847723515b&start={FirstLong},{FirstLat}&end={SecLong},{SecLat}", method="GET", headers=headers) response_dict = await response.json() # create coordinates object, append it to the coords list for export to javascript coordinates = response_dict['features'][0]['geometry']['coordinates'] route.extend(coordinates) route.insert(0, [float(FirstLong), float(FirstLat)]) route.append([float(SecLong), float(SecLat)]) #lon1, lat1, lon2, lat2 route_diffs = [] for i in route: # switch from LongLat to LatLong i[0], i[1] = i[1], i[0] for i in range(len(route)): # need to use range len idiom (bad practice) to grab next index value without using itertools try: # pairwise calculation of lat longs in georoute lat1 = route[i][0] lon1 = route[i][1] lat2 = route[i + 1][0] lon2 = route[i + 1][1] difference = haversine(lon1 = lon1, lat1 = lat1, lon2 = lon2, lat2= lat2) route_diffs.append(difference) except IndexError: break finaldist = sum(route_diffs) # Uncomment this if you would like to see the full route lat long array printed #pyscript.write('storage', route) pyscript.write('distance', f'Distance from A to B: {finaldist:.2f} km') def setup(): """ Initializes site content and HTML listeners that are typically handled by JavaScript """ click_proxy = create_proxy(button_click) e = document.getElementById("button") e.addEventListener("click", click_proxy) setup()