I was working with geographical data that contained latitude-longitude pairs this week. I needed to compute the area (in square kilometers or square miles) of a rectangle bounded by four latitude-longitude locations. There are at least two problems here. First, the earth is not flat so the curvature needs to be taken into account. Second, the distance represented by one degree of longitude varies depending on where you are on the globe. Latitude values range from -90.0 to +90.0 and represent up-down position. A latitude of 0.0 is the equator. Longitude values range from -180.0 to +180.0 and represent left-right position. A longitude of 0.0 is the Prime Meridian and runs through Greenwich, England. Imagine the earth as a peeled orange. As longitude lines (the orange segments) get closer to the poles, the distance between the lines becomes smaller and smaller.

One approach for computing geographical area is to first define a distance function between any two locations. Here’s a C# implementation:

static double Distance(double lat1, double lon1, double lat2, double lon2)

{

double r = 6371.0; // approx. radius of earth in km

double lat1Radians = (lat1 * Math.PI) / 180.0;

double lon1Radians = (lon1 * Math.PI) / 180.0;

double lat2Radians = (lat2 * Math.PI) / 180.0;

double lon2Radians = (lon2 * Math.PI) / 180.0;

double d = r * Math.Acos((Math.Cos(lat1Radians) *

Math.Cos(lat2Radians) *

Math.Cos(lon2Radians – lon1Radians) +

(Math.Sin(lat1Radians) * Math.Sin(lat2Radians)));

return d;

}

This is just a simple approximation. There is an alternative distance computation formula that uses the so-called haversine technique. Now we can compute the width and height between any two points, and then multiply to get an approximate area:

static double Area(double lat1, double lon1, double lat2, double lon2)

{

// lat1-lon1 is the upper-left corner, lat2-lon2 is the lower-right

double height = Distance(lat1,lon1, lat2,lon1);

double width = Distance(lat1,lon1, lat1,lon2);

return height * width;

}

Pretty crude, but for my purposes, just what I needed.