Calculating Distance Between 2 Cities [closed]

2020-02-16 20:47发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 5 years ago.

How do you calculate the distance between 2 cities?

回答1:

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



回答2:

You use the Haversine formula.



回答3:

This is very easy to do with geography type in SQL Server 2008.

SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))
-- computes distance in meters using eliptical model, accurate to the mm

4326 is SRID for WGS84 elipsoidal Earth model



回答4:

You ca use the A* algorithm to find the shortest path between those two cities and this way you'll have the distance.



回答5:

If you're talking about the shortest distance between two real cities on a real spherical planet, like Earth, you want the great circle distance.



回答6:

If you are working in the plane and you want the Euclidean distance "as the crow flies":

// Cities are points x0,y0 and x1,y1 in kilometers or miles or Smoots[1]
dx = x1 - x0;
dy = y1 - y0;
dist = sqrt(dx*dx + dy*y);

No trigonometry needed! Just the Pythagorean theorem 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().

Note that you could probably do this in one line and a compiler would probably reduce it the equivalent above code:

dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));

[1] http://en.wikipedia.org/wiki/Smoot



回答7:

You can get the distance between two cities from google map api. Here is an implementation of it in Python

#!/usr/bin/python
import requests
from sys import argv 
def get_distance(origin,destination):
    gmap='http://maps.googleapis.com/maps/api/distancematrix/json'
    payload={"origins":origin,"destinations":destination,"sensor":'false' }
    try:
        a=requests.get(gmap,params=payload)
        data = a.json()
        origin = str(data['origin_addresses'][0])
        destination= str(data['destination_addresses'][0])
        distance = data['rows'][0]['elements'][0]['distance']['text']
        return distance,origin,destination
    except Exception,e:
        print "The %s or %destination does not exists :(" %(origin,destination)
        exit()

if __name__=="__main__":
    if len(argv)<3:
        print "sorry Check the format"
    else:
        origin=argv[1]
        destination=argv[2]
        distance,origin,destination=get_distance(origin,destination)
        print "%s ---> %s    :   %s" %(origin,destination,distance)

Example link: https://gist.github.com/sarathsp06/cf063e47bcc515b51c84



回答8:

You find the Lat/Lon of the city, then use a distance estimation algorithm for Lat/Lon coordinates.



回答9:

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



回答10:

It is better to use a look-up table for obtaining the distance between two cities.

This makes sense because * The Formula to calculate the distance ais quite computationally intensive.. * Distance between cities is unlikely to change.

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.



回答11:

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.

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).

The real trick is getting the lat and long..for that I'm using Google.



回答12:

@Jared - a minor correction to your code example. The last line of the first code example should read:

dist = sqrt(dx*dx + dy*dy);


回答13:

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 Wikipedia's entry on the Vincenty algorithm 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 geographicLib, which purports to be 1000 time more accurate than the Vincenty algorithm (if you have data that good, it might matter).

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.



回答14:

i use distancy so simple and clean