Under the Bridge

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!

3
  • http://www.coders4fun.com Dzamir

    Wow! Just what I need for my new software :-)

  • Andy

    If you’re handling lats and longs then you’re probably dealing with CLLocations (or can instantiate on), so you could always just use CLLocation’s getDistanceFrom: method. This method might also take into account the non-spherical shape of the earth (it’s not obvious from the description).

  • http://www.alexcurylo.com/ Alex

    True, if you’re on the device — but for your server/desktop client side code, you’ll need to do it yourself.