[GIS] Using GDAL/C++ to calculate distance in meters

cdistancegdal

I'm using GDAL in C++, with WGS84. I want to calculate distance between two points in meters. The code snippet below tries to find the distance between 25N/75E and 25N/76E. The code, as is, returns 1.0000, which is just a Cartesian number. I need the answer in meters or feet or miles. How do I do that?

OGRSpatialReference  wgs84;
OGRPoint   point1,
           point2;

assert(wgs84.SetWellKnownGeogCS("WGS84")==OGRERR_NONE);
point1.assignSpatialReference(&wgs84);
point2.assignSpatialReference(&wgs84);
point1.setY(25.0000); point1.setX(75.0000);
printf("Distance %f\n",point1.Distance(&point2));

point2.setY(25.0000); point2.setX(76.0000);
printf("Distance %f\n",point1.Distance(&point2)); 

Best Answer

GDAL depends on Proj.4 and the latest version of Proj.4 (4.9.1) includes an API for geodesic calculations (and the geod command uses this API). This is a translation of the C++ geodesic routines in GeographicLib to C. The documentation on the C interface is here. Alternatively, you can use the C++ interface of GeographicLib directly (GeographicLib and GDAL won't interfere with one another). I recommend against implementing Vincenty's algorithm, because it doesn't always converge.

An example of using the C interface is inverse.c.

An example of using the C++ interface is given here (search for "Example of use").