const posts = [
{
name: 'Berlin',
latitude: '52.520008',
longitude: '13.404954',
},
{
name: 'Hamburg',
latitude: '53.551086',
longitude: '9.993682',
},
{
name: 'München',
latitude: '48.135124',
longitude: '11.581981',
},
{
name: 'Lübeck',
latitude: '53.865467',
longitude: '10.686559',
},
{
name: 'Schwerin',
latitude: '53.635502',
longitude: '11.401250',
},
];
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
const R = 6371; // Radius of the earth in km
const dLat = deg2rad(lat2-lat1); // deg2rad below
const dLon = deg2rad(lon2-lon1);
const 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)
;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
function findClosePosts(location, radius, posts) {
return posts.filter((post) =>
// find close points within the radius of the location, but exclude the location itself from results
getDistanceFromLatLonInKm(location.latitude, location.longitude, post.latitude, post.longitude) <= radius && location !== post);
}
function findLocationByName(name, posts) {
return posts.find((post) => post.name === name);
}
const hamburg = findLocationByName('Hamburg', posts);
const closePosts = findClosePosts(hamburg, 200, posts);
console.log(closePosts);