Answer the question
In order to leave comments, you need to log in
How to find the nearest point from an array?
Good day.
There are client coordinates:
// Пример
const lat = 56.4063789;
const lon = 38.7151217;
[
{
address: 'ул Тестовская, 1',
city: 'Москва',
id: 14766,
latitude: '55.7479019',
longitude: '37.532949'
},
{
address: 'ул 1-я Тверская-Ямская, 2',
city: 'Москва',
id: 12863,
latitude: '55.770302',
longitude: '37.597099'
}
//....
];
Answer the question
In order to leave comments, you need to log in
const closest = arr.reduce((closest, n) => {
const distance = sphericalDistance(
{ lat, lon },
{ lat: n.latitude, lon: n.longtitude }
);
return distance < closest.distance
? { item: n, distance }
: closest;
}, {
item: null,
distance: Infinity,
}).item;
function sphericalDistance(p1, p2) {
// https://en.wikipedia.org/wiki/Great-circle_distance
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question