Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
cómo obtener múltiples ubicaciones cercanas según el rango usando haversine reactjs

Estoy creando una aplicación que puede brindar ubicaciones cercanas y estoy tratando de mostrar algunas ubicaciones cercanas. pero solo puedo generar solo 1 ubicación más cercana. Necesito al menos 5 ubicaciones más cercanas y ordenadas por ranking

Lo que he probado hasta ahora

Paquete NPM utilizado para obtener la distancia entre ubicaciones

 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 answers
Answer question

0

De acuerdo con el enlace que ha proporcionado; la biblioteca que está utilizando solo recuperará LA ubicación más cercana (solo una; la ubicación más cercana) de las ubicaciones que especifique.

La manera en que lo veo; tienes dos opciones

Opción 1:

Puede llamar a la función findNearestLocation dentro de un bucle; y elimine la ubicación más cercana devuelta de la biblioteca de su conjunto de ubicaciones.

De esa manera, cada vez que llame a la función findNearestLocation , eliminará la cantidad de opciones en el orden de distancia (más cercano a más lejano)

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);

Opcion 2:

Si está utilizando la biblioteca para recuperar solo la ubicación más cercana; puede eliminar la dependencia implementando la fórmula de Haversine usted mismo. Puede consultar esta pregunta y respuesta de SO .

Y puede modificar la función para devolver las ubicaciones en el orden de su distancia desde su ubicación.

 // 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; });

La siguiente función "haversineDistance" se extrae del enlace anterior y el crédito es para @Nathan Lippi y @talkol. Función Haversine Distance: fuente original

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!