Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created Sep 7, 2022
Embed
What would you like to do?
const calcularDistanciaEntreDosCoordenadas = (lat1, lon1, lat2, lon2) => {
// Convertir todas las coordenadas a radianes
lat1 = gradosARadianes(lat1);
lon1 = gradosARadianes(lon1);
lat2 = gradosARadianes(lat2);
lon2 = gradosARadianes(lon2);
// Aplicar fórmula
const RADIO_TIERRA_EN_KILOMETROS = 6371;
let diferenciaEntreLongitudes = (lon2 - lon1);
let diferenciaEntreLatitudes = (lat2 - lat1);
let a = Math.pow(Math.sin(diferenciaEntreLatitudes / 2.0), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(diferenciaEntreLongitudes / 2.0), 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return RADIO_TIERRA_EN_KILOMETROS * c;
};
const gradosARadianes = (grados) => {
return grados * Math.PI / 180;
};
//CDMX
//19.416326917410476, -99.12479042256915
const cdmx = {
latitud: 19.416326917410476,
longitud: -99.12479042256915,
};
// La habana
// 23.097069089850933, -82.35006433419622
const habana = {
latitud: 23.097069089850933,
longitud: -82.35006433419622,
};
const distanciaEnKilometros = calcularDistanciaEntreDosCoordenadas(cdmx.latitud, cdmx.longitud, habana.latitud, habana.longitud);
console.log(distanciaEnKilometros);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment