If I have the latitude and longitude of a specific location and I need to return all of the towns/cities that are within a certain distance of this location e.g. 1 to 500 miles as text on a webpage. How would I do this in Javascript in conjunction with https://positionstack.com/?
For an exact calculation (well, the earth is not exacty spherical ...) you will need to go through the spherical distance equation found here https://www.geeksforgeeks.org/program-distance-two-points-earth
const [sin,cos]=["sin","cos"].map(fn=>x=>Math[fn](x/180*Math.PI)), // sin, cos in degree
r = 3963, // earth radius in miles (in km: 6371)
dist = r * Math.acos(sin(lat0)*sin(lat) + cos(lat0)*cos(lat)*cos(long-long0))
So, you would have to calculate the distance from the centre point for potential lat/long pair in order to determine whether the distance is smaller or larger than 500 miles.
const places=[
["Ottawa",45.43026089850648, -75.70148893316303],
["Montreal",45.523098477377275, -73.63711795099447],
["Montpelier,VT",44.25960673881783, -72.58589897991801],
["Charleston,SC",32.781829336634694, -79.95973326005715],
["Atlanta,GA",33.76477968890186, -84.39589310326373]],
lat0=38.8977597229071, long0=-77.03654054271286, // White House coords.
r=3963, // earth's radius
[sin,cos]=["sin","cos"].map(fn=>x=>Math[fn](x/180*Math.PI)), // sin(deg), cos(deg)
sinlat0=sin(lat0),coslat0=cos(lat0),
showDist=(place,lat,long)=>{
const dist = r * Math.acos(sinlat0*sin(lat) + coslat0*cos(lat)*cos(long-long0))
console.log(place,dist.toFixed(2));
}
console.log("Distances from the White House (in miles):");
places.forEach(p=>showDist(...p));
console.log("\nOr, taking output from https://positionstack.com:");
const d={"data":[{"latitude":40.68295,"longitude":-73.9708,"type":"locality","name":"New York","number":null,"postal_code":null,"street":null,"confidence":1,"region":"New York","region_code":"NY","county":"Kings County","locality":"New York","administrative_area":null,"neighbourhood":null,"country":"United States","country_code":"USA","continent":"North America","label":"New York, NY, USA"},{"latitude":40.777048,"longitude":-73.967596,"type":"borough","name":"Manhattan","number":null,"postal_code":null,"street":null,"confidence":1,"region":"New York","region_code":"NY","county":"New York County","locality":"New York","administrative_area":null,"neighbourhood":null,"country":"United States","country_code":"USA","continent":"North America","label":"Manhattan, New York, NY, USA"},{"latitude":40.775105,"longitude":-73.968777,"type":"county","name":"New York County","number":null,"postal_code":null,"street":null,"confidence":0.4,"region":"New York","region_code":"NY","county":"New York County","locality":null,"administrative_area":null,"neighbourhood":null,"country":"United States","country_code":"USA","continent":"North America","label":"New York County, NY, USA"}]};
d.data.forEach(p=>showDist(p.name,p.latitude,p.longitude))