Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active September 16, 2021 20:25
Show Gist options
  • Save EduardoSP6/b5ad71f746c84c2b911ca44c4432bd2d to your computer and use it in GitHub Desktop.
Save EduardoSP6/b5ad71f746c84c2b911ca44c4432bd2d to your computer and use it in GitHub Desktop.
Distance between two coordinates - Java
public static double calcDistanceBetweenCoords(Double origLat, Double origLng, Double destLat, Double destLng)
{
double result = 0;
if (origLat == null || origLng == null || destLat == null || destLng == null) {
return result;
}
// converte as coordenadas para radianos
origLat = Math.toRadians(origLat);
origLng = Math.toRadians(origLng);
destLat = Math.toRadians(destLat);
destLng = Math.toRadians(destLng);
// earth radius in quilometers
int earthRadius = 6371;
// adjust of 16% for better proximity to reality
double adjust = 1.16;
result = (earthRadius * Math.acos(Math.cos(origLat) * Math.cos(destLat) * Math.cos(destLng - origLng) + Math.sin(origLat) * Math.sin(destLat)));
result *= adjust;
return result; // result in km
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment