I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items.
While I successfully managed to filter the data based on cities like "Hong Kong" and count them using a simple comparison, calculating distances introduces another layer of complexity to the data filtering process.
coords = [
{
City: "Hong Kong",
Lat: “22.667790”,
Long: “-111.909905”
},
{
City: "Atlanta",
Lat: “22.958769”,
Long: “-111.948939”
},
{
City: "Paris",
Lat: “23.989803”,
Long: “-112.989850”
},
{
City: "Sydney",
Lat: “22.001118”,
Long:”-111.939433”
},
{
City: "Hong Kong",
Lat: “22.667790”,
Long: “-111.909905”
}
];
origin = {
lat:"22.111009",
long: "-113.667870"
};
function getDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2 - lat1); // deg2rad below
var dLon = deg2rad(lon2 - lon1);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI / 180);
}
var filteredCities = coords.filter(function(coord){
distance = getDistance(coord.lat, coord.long, origin.lat, origin.long);
if (distance < 10){
return true;
}
});
console.log("Number of cities within 10km of the origin: ", filteredCities.length);
So far, my attempts have only resulted in generating a list of distances between the origin and each object. The goal is to determine how many cities are situated within a 10km range of the given origin point.