I have many points on Google Maps
and I want to show for each point the nearest city (so a reverse geocoding).
I have a multidimensional array like this:
Since the city data is not dynamically changed and you need to calculate the distance / nearest neighbour frequently, using a geospatial index (KD-Tree, R-Tree etc) would make sense.
Here's an example implementation using geokdbush which is based on a static spatial index implemented using a KD-Tree. It takes Earth curvature and date line wrapping into account.
const kdbush = require('kdbush');
const geokdbush = require('geokdbush');
// I've stored the data points as objects to make the values unambiguous
const cities = [
{ name: "Abano Terme (PD)", latitude: 45.3594, longitude: 11.7894 },
{ name: "Abbadia Cerreto (LO)", latitude: 45.3122, longitude: 9.5928 },
{ name: "Abbadia Lariana (LC)", latitude: 45.8992, longitude: 9.3336 },
{ name: "Abbadia San Salvatore (SI)", latitude: 42.8800, longitude: 11.6775 },
{ name: "Abbasanta (OR)", latitude: 40.1250, longitude: 8.8200 }
];
// Create the index over city data ONCE
const index = kdbush(cities, ({ longitude }) => longitude, ({ latitude }) => latitude);
// Get the nearest neighbour in a radius of 50km for a point with latitude 43.7051 and longitude 11.4363
const nearest = geokdbush.around(index, 11.4363, 43.7051, 1, 50);
Once again, bear in mind that kdbush is a static index and cannot be changed (you cannot add or remove cities from it). If you need to change the city data after initialisation, depending on how often you do it, using an index might prove too costly.