Archive for August 23rd, 2009

Snippet: Distance Calculation

So, if you’re doing a GPS-enabled application, chances are you’re going to want to figure out distances sooner or later. Perhaps even, as in this iphonesdk thread, have a SQL database of points of interest and want to pick nearby ones. And here is how you would construct that kind of query:

sprintf(buffer, "SELECT * FROM POIs WHERE (ABS(lat - %f) < 0.03) AND (ABS(lng - %f) < 0.04);", nLat, nLon);

Handy, that. And if you really need exact distance sorting, here is a formula that works at any latitude:

//spherical distance in meters
- (CGFloat) sphericalDistanceFromLat1:(CGFloat)lat1 Lon1:(CGFloat)lon1
      toLat2:(CGFloat)lat2 Lon2:(CGFloat)lon2
{
   return acos(sin(lat1 * 0.0174533) * sin(lat2 * 0.0174533)
      + cos(lat1 * 0.0174533)
        * cos(lat2 * 0.0174533)
        * cos((lon2-lon1) * 0.0174533))
        * 6371000;
}

Now you know!

Continue Reading →
3