<p>How do you calculate the distance between 2 cities? </p>

[{'answer_id': 23575, 'author': 'EndangeredMassa', 'author_id': 106, 'author_profile': 'https://Stackoverflow.com/users/106', 'pm_score': 0, 'selected': False, 'text': '<p>You find the Lat/Lon of the city, then use a distance estimation algorithm for Lat/Lon coordinates.</p>\n'}, {'answer_id': 23579, 'author': 'Ian Nelson', 'author_id': 2084, 'author_profile': 'https://Stackoverflow.com/users/2084', 'pm_score': 3, 'selected': False, 'text': '<p>You use the <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">Haversine formula</a>.</p>\n'}, {'answer_id': 23591, 'author': 'Michał Piaskowski', 'author_id': 1534, 'author_profile': 'https://Stackoverflow.com/users/1534', 'pm_score': 1, 'selected': False, 'text': '<p>You ca use the <a href="http://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow noreferrer">A*</a> algorithm to find the shortest path between those two cities and this way you\'ll have the distance.</p>\n'}, {'answer_id': 23593, 'author': 'jonezy', 'author_id': 2272, 'author_profile': 'https://Stackoverflow.com/users/2272', 'pm_score': 0, 'selected': False, 'text': '<p>if you need a code example I think I have one I could dig up at home, but like many of the previous answers, you need a long / lat db to do the calculation</p>\n'}, {'answer_id': 23615, 'author': 'Pascal', 'author_id': 1311, 'author_profile': 'https://Stackoverflow.com/users/1311', 'pm_score': 0, 'selected': False, 'text': '<p>It is better to use a look-up table for obtaining the distance between two cities. </p>\n\n<p>This makes sense because\n* The Formula to calculate the distance ais quite computationally intensive..\n* Distance between cities is unlikely to change.</p>\n\n<p>So unless you needs are very specific (like terrain mapping from a satellite or some or topography algorithm or something else), you should really just save the list of cities and distances between them, into a table and look it up as needed.</p>\n'}, {'answer_id': 23632, 'author': 'Jared Updike', 'author_id': 2543, 'author_profile': 'https://Stackoverflow.com/users/2543', 'pm_score': 1, 'selected': False, 'text': '<p>If you are working in the plane and you want the <a href="http://en.wikipedia.org/wiki/Euclidean_distance" rel="nofollow noreferrer">Euclidean distance</a> "as the crow flies":</p>\n\n<pre><code>// Cities are points x0,y0 and x1,y1 in kilometers or miles or Smoots[1]\ndx = x1 - x0;\ndy = y1 - y0;\ndist = sqrt(dx*dx + dy*y);\n</code></pre>\n\n<p>No trigonometry needed! Just the <a href="http://en.wikipedia.org/wiki/Pythagorean_theorem" rel="nofollow noreferrer">Pythagorean theorem</a> and the fact that squares are always positive so you don\'t need dx = abs(x1 - x0), etc. to get a positive number to pass to sqrt().</p>\n\n<p>Note that you could probably do this in one line and a compiler would <em>probably</em> reduce it the equivalent above code:</p>\n\n<pre><code>dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));\n</code></pre>\n\n<p>[1] <a href="http://en.wikipedia.org/wiki/Smoot" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Smoot</a></p>\n'}, {'answer_id': 23650, 'author': 'Mike Powell', 'author_id': 205, 'author_profile': 'https://Stackoverflow.com/users/205', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re talking about the shortest distance between two real cities on a real spherical planet, like Earth, you want the <a href="http://en.wikipedia.org/wiki/Great-circle_distance" rel="nofollow noreferrer">great circle distance</a>.</p>\n'}, {'answer_id': 23700, 'author': 'Dana the Sane', 'author_id': 2567, 'author_profile': 'https://Stackoverflow.com/users/2567', 'pm_score': 6, 'selected': True, 'text': '<p>If you need to take the curvature of the earth into account, the Great-Circle distance is what you\'re looking for. <a href="http://en.wikipedia.org/wiki/Great-circle_distance" rel="nofollow noreferrer">The Wikipedia article</a> probably does a better job of explaining how the formula works than me, and there\'s also <a href="http://www.edwilliams.org/avform.htm" rel="nofollow noreferrer">this aviation formulary page</a> that covers that goes into more detail.</p>\n\n<p>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 <a href="http://www.geonames.org/" rel="nofollow noreferrer">Geonames.org</a>, 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 <a href="http://en.wikipedia.org/wiki/Great-circle%5Fdistance#Worked_example" rel="nofollow noreferrer">the Wikipedia Worked Example</a>.</p>\n\n<p>Other suggestions:</p>\n\n<ul>\n<li>For a full commercial solution,\nthere\'s <a href="http://www.alk.com/pcmiler/pcmiler-system-req.asp" rel="nofollow noreferrer">PC Miler</a> which is used\nby many trucking companies to\ncalculate shipping rates.</li>\n<li>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.</li>\n<li>Also <strong>very important</strong> 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.</li>\n</ul>\n\n<p>Last but not least, Joel wrote an article about this problem a while back, so here you go: <a href="http://www.joelonsoftware.com/items/2006/10/09.html" rel="nofollow noreferrer">New Feature: Job Search</a></p>\n'}, {'answer_id': 23731, 'author': 'Webjedi', 'author_id': 1975, 'author_profile': 'https://Stackoverflow.com/users/1975', 'pm_score': 0, 'selected': False, 'text': "<p>I've been doing a lot of work with this recently.  I'm finding SQL2008's new features really make this easy.  I can find all the points that are withing Xkm of a 100k record table in sub-second time...not too shabby.</p>\n\n<p>The great circle (spherical assumption) method in my testing was about 2.5 miles off when compared to the vincenty formula (elipsoidal assumption, which is what the earth is).  </p>\n\n<p>The real trick is getting the lat and long..for that I'm using Google.</p>\n"}, {'answer_id': 23746, 'author': 'Josh Brown', 'author_id': 2030, 'author_profile': 'https://Stackoverflow.com/users/2030', 'pm_score': 0, 'selected': False, 'text': '<p>@Jared - a minor correction to your code example. The last line of the first code example should read:</p>\n\n<pre><code>dist = sqrt(dx*dx + dy*dy);\n</code></pre>\n'}, {'answer_id': 501226, 'author': 'Marko Tintor', 'author_id': 61003, 'author_profile': 'https://Stackoverflow.com/users/61003', 'pm_score': 2, 'selected': False, 'text': '<p>This is very easy to do with geography type in SQL Server 2008.</p>\n\n<pre><code>SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))\n-- computes distance in meters using eliptical model, accurate to the mm\n</code></pre>\n\n<p>4326 is SRID for WGS84 elipsoidal Earth model</p>\n'}, {'answer_id': 5236797, 'author': 'Stonetip', 'author_id': 597231, 'author_profile': 'https://Stackoverflow.com/users/597231', 'pm_score': 0, 'selected': False, 'text': '<p>I agree that once you have the info, if it\'s not going to change, store it somehow. @Marko Tinto Thanks for the T-SQL sample. For those who don\'t have access to SQL Server or prefer another method: If you need high accuracy, check out <a href="http://en.wikipedia.org/wiki/Vincenty%27s_algorithm" rel="nofollow">Wikipedia\'s entry on the Vincenty algorithm</a> for more info. I believe there is a js implementation, which would (if not already) be easily ported to other languages. Also, at the bottom of that page is a link to <a href="http://geographiclib.sourceforge.net/" rel="nofollow">geographicLib</a>, which purports to be 1000 time more accurate than the Vincenty algorithm (if you have data that good, it might matter).</p>\n\n<p>Why would you use something like the Vincenty method? Because the earth is not a perfect sphere and methods like that allow for inputting a more accurate major and minor axis for modeling the earth. </p>\n'}, {'answer_id': 10889470, 'author': 'user1436185', 'author_id': 1436185, 'author_profile': 'https://Stackoverflow.com/users/1436185', 'pm_score': 0, 'selected': False, 'text': '<p>i use <a href="http://www.distancy.com" rel="nofollow" title="distance between cities">distancy</a> \nso simple and clean</p>\n'}, {'answer_id': 24403838, 'author': 'Sarath Sadasivan Pillai', 'author_id': 1898494, 'author_profile': 'https://Stackoverflow.com/users/1898494', 'pm_score': 1, 'selected': False, 'text': '<p>You can get the distance between two cities from google map api.\nHere is an implementation of it in Python</p>\n\n<pre><code>#!/usr/bin/python\nimport requests\nfrom sys import argv \ndef get_distance(origin,destination):\n    gmap=\'http://maps.googleapis.com/maps/api/distancematrix/json\'\n    payload={"origins":origin,"destinations":destination,"sensor":\'false\' }\n    try:\n        a=requests.get(gmap,params=payload)\n        data = a.json()\n        origin = str(data[\'origin_addresses\'][0])\n        destination= str(data[\'destination_addresses\'][0])\n        distance = data[\'rows\'][0][\'elements\'][0][\'distance\'][\'text\']\n        return distance,origin,destination\n    except Exception,e:\n        print "The %s or %destination does not exists :(" %(origin,destination)\n        exit()\n\nif __name__=="__main__":\n    if len(argv)&lt;3:\n        print "sorry Check the format"\n    else:\n        origin=argv[1]\n        destination=argv[2]\n        distance,origin,destination=get_distance(origin,destination)\n        print "%s ---&gt; %s    :   %s" %(origin,destination,distance)\n</code></pre>\n\n<p>Example link: <a href="https://gist.github.com/sarathsp06/cf063e47bcc515b51c84" rel="nofollow">https://gist.github.com/sarathsp06/cf063e47bcc515b51c84</a></p>\n'}]
['https://Stackoverflow.com/questions/23569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2141/']