Given a json file,
{"BusStopCode": "00481", "RoadName": "Woodlands Rd", "Description": "BT PANJANG TEMP BUS PK", "Latitude": 1.383764, "Longitude": 103.7583},
{"BusStopCode": "01012", "RoadName": "Victoria St", "Description": "Hotel Grand Pacific", "Latitude": 1.29684825487647, "Longitude": 103.85253591654006}
, and so on..
of various bus stops, I am trying to find the nearest bus stops based on this list of 5000 bus stops with any user given lat/long using the given formula
import math
R = 6371000 #radius of the Earth in m
x = (lon2 - lon1) * cos(0.5*(lat2+lat1))
y = (lat2 - lat1)
d = R * sqrt( x*x + y*y )
My question would be, for user input of lat1 and lon1, how would i be able to compute all distances between lat1 lon1 and lat2 lon2 (where lat2 lon2 will take the value of all 5000 lat/lon in json file), and then print the lowest 5 distances?
I have thought of using list.sort but am not sure of how i am able to compute all 5000 distances using python.
Thank you so much.
Edit:
With the code from Eric Duminil, the following code works for my needs.
from math import cos, sqrt
import sys
import json
busstops = json.loads(open("stops.json").read())
R = 6371000 #radius of the Earth in m
def distance(lon1, lat1, lon2, lat2):
x = (lon2-lon1) * cos(0.5*(lat2+lat1))
y = (lat2-lat1)
return R * sqrt( x*x + y*y )
buslist = sorted(busstops, key= lambda d: distance(d["Longitude"], d["Latitude"], 103.5, 1.2))
print(buslist[:5])
where 103.5, 1.2 from buslist is an example user input longitude latitude.