S
S
Sergey2021-07-15 15:31:06
JavaScript
Sergey, 2021-07-15 15:31:06

How to find the nearest point from an array?

Good day.

There are client coordinates:

// Пример
const lat = 56.4063789;
const lon = 38.7151217;


There is an array with all points, inside which you need to find the one closest to the client:
[
      {
        address: 'ул Тестовская, 1',
        city: 'Москва',
        id: 14766,
        latitude: '55.7479019',
        longitude: '37.532949'
      },
      {
        address: 'ул 1-я Тверская-Ямская, 2',
        city: 'Москва',
        id: 12863,
        latitude: '55.770302',
        longitude: '37.597099'
      }
     //....
    ];


I would be grateful for any hint.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-07-15
@justedoit

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
}

W
Wataru, 2021-07-15
@wataru

R-tree .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question