Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
how to get multiple nearby locations based on rank using haversine reactjs

i'm making an app that can give nearby locations and i'm trying to show some nearby locations. but i can only generate only 1 nearest location. I need at least 5 locations that are closest and sorted by ranking

What I have tried so far

NPM package used to get the distance between locations

var locations = [......]; // your locations array
var nearestLocations = [];
for (let step = 0; step < 5; step++) {
// check if locations are exhausted


if(locations.length == 0) break;


// get the nearest location


let nearest = findNearestLocation(myLocation, locations);


// push the nearest location


nearestLocations.push(nearest);
console.log(step);
console.log(nearest);



// remove the retrieved location from the locations array


locations = locations.filter(function( location ) {
return (location.lat !== nearest.lat && location.lng !== nearest.lng);
  });
}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

According to the link you have provided; the library you are using will only retrieve THE nearest location (only one; the nearest location) out of the locations you specify.

The way I see it; you have two options.

Option 1:

You can call the findNearestLocation function inside a loop; and remove the nearest location returned from the library from your array of locations.

That way, everytime you call the findNearestLocation function, you will eliminate the number of choices in the order of distance (nearest to furthest)

Ex:

var locations = [......]; // your locations array
var nearestLocations = [];
for (let step = 0; step < 5; step++) {
  // check if locations are exhausted
  if(locations.length == 0) break;
  // get the nearest location
  let nearest = findNearestLocation(myLocation, locations);
  // push the nearest location
  nearestLocations.push(nearest);
  // remove the retrieved location from the locations array
  locations = locations.filter(function( location ) {
    return (location.lat !== nearest.lat && location.lng !== nearest.lng);
  });
}
// after the loop completes; you can print the array to view the nearest locations.
console.log(nearestLocations);

Option 2:

If you are using the library to only retrieve the nearest location; you can eliminate the dependency by implementing the Haversine formula yourself. You can refer this SO question and answer.

And you can modify the function to return the locations in the order of their distance from your location.

// Sort your locations array by distance (nearest to furthest)
var myLocation = // get your current location
locations.sort(function(a, b) {
  let distanceA = haversineDistance(myLocation, a);
  let distanceB = haversineDistance(myLocation, b);
  // Compare the 2 distances
  if (distanceA < distanceB) return -1;
  if (distanceA > distanceB) return 1;
  return 0;
});

The below "haversineDistance" function is extracted from the above link and credit goes to @Nathan Lippi and @talkol. Haversine Distance function: original source

function haversineDistance(coords1, coords2, isMiles = false) {
  function toRad(x) {
    return x * Math.PI / 180;
  }

  var lon1 = coords1[0];
  var lat1 = coords1[1];

  var lon2 = coords2[0];
  var lat2 = coords2[1];

  var R = 6371; // km

  var x1 = lat2 - lat1;
  var dLat = toRad(x1);
  var x2 = lon2 - lon1;
  var dLon = toRad(x2)
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) * Math.cos(toRad(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;

  if(isMiles) d /= 1.60934;

  return d;
}
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda