Search code examples
algorithmmathtrigonometrygeography

Calculating Distance Between 2 Cities


How do you calculate the distance between 2 cities?


Solution

  • If you need to take the curvature of the earth into account, the Great-Circle distance is what you're looking for. The Wikipedia article probably does a better job of explaining how the formula works than me, and there's also this aviation formulary page that covers that goes into more detail.

    The formulas are only the first part of the puzzle though, if you need to make this work for arbitrary cities, you'll need a location database to get the lat/long from. Luckily you can get this for free from Geonames.org, although there are commercial db's available (ask google). So, in general, look up the two cities you want, get the lat/long co-orinates and plug them into the formula as in the Wikipedia Worked Example.

    Other suggestions:

    • For a full commercial solution, there's PC Miler which is used by many trucking companies to calculate shipping rates.
    • Make calls to the Google Maps (or other) api. If you need to do many requests per day, consider caching the results on the server.
    • Also very important is to consider building an equivalence database for cities, suburbs, towns etc. if you think you'll ever need to group your data. This gets really complicated though, and you may not find a one-size-fits-all solution for your problem.

    Last but not least, Joel wrote an article about this problem a while back, so here you go: New Feature: Job Search