Skip to content

Instantly share code, notes, and snippets.

@clydebarrow
Last active June 19, 2022 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clydebarrow/75e3d950f9c7c7f328b03243e11cbf3c to your computer and use it in GitHub Desktop.
Save clydebarrow/75e3d950f9c7c7f328b03243e11cbf3c to your computer and use it in GitHub Desktop.
Command line utility to calculate great circle distance using the spherical law of cosines
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static double getRadians(const char * str, double limit, const char * msg) {
char * endptr;
double val = strtod(str, &endptr);
if(endptr != str && val < limit && val > -limit)
return val * 0.0174533; // convert to radians
fprintf(stderr, "Invalid value for %s: %s\n", msg, str);
exit(1);
}
int main(int argc, char ** argv) {
if(argc < 5) {
fprintf(stderr, "Usage: greatcircle lat1 lon1 lat2 lon2\n");
exit(1);
}
double y1 = getRadians(argv[1], 90.0, "start latitude");
double x1 = getRadians(argv[2], 180.0, "start longitude");
double y2 = getRadians(argv[3], 90.0, "end latitude");
double x2 = getRadians(argv[4], 180.0, "end longitude");
double angle1 = acos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2));
double distance = angle1 * 60.0 / 0.0174533 * 1852;
printf("%f\n", distance); // distance in metres
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment