Distance between 2 geocodes

前端 未结 9 1418
一生所求
一生所求 2020-12-05 22:10

What is the formula for calculating the distance between 2 geocodes? I have seen some of the answers on this site but they basically say to rely on SQL Server 08 functions,

相关标签:
9条回答
  • 2020-12-05 22:53

    The pythagorean theorem as offered up by others here doesn't work so well.

    The best, simple answer is to approximate the earth as a sphere (its actually a slightly flattened sphere, but this is very close). In Haskell, for instance you might use the following, but the math can be transcribed into pretty much anything:

    distRadians (lat1,lon1) (lat2,lon2) = 
        radius_of_earth * 
        acos (cos lat1 * cos lon1 * cos lat2 * cos lon2 + 
              cos lat1 * sin lon1 * cos lat2 * sin lon2 + 
              sin lat1 * sin lat2) where
        radius_of_earth = 6378 -- kilometers
    
    
    distDegrees a b = distRadians (coord2rad a) (coord2rad b) where
        deg2rad d = d * pi / 180
        coord2rad (lat,lon) = (deg2rad lat, deg2rad lon)
    

    distRadians requires your angles to be given in radians.

    distDegrees is a helper function that can take lattitudes and longitudes in degrees.

    See this series of posts for more information on the derivation of this formula.

    If you really need the extra precision granted by assuming the earth is ellipsoidal, see this FAQ: http://www.movable-type.co.uk/scripts/gis-faq-5.1.html

    0 讨论(0)
  • 2020-12-05 22:54

    Take a look here for a SQL server 2000 version SQL Server Zipcode Latitude/Longitude proximity distance search

    0 讨论(0)
  • 2020-12-05 22:56

    If

    • you know that the 2 points are "not too far from each other"
    • and you tolerate a "reasonably small" error.

    Then, consider that the earth is flat between the 2 points :

    • The distance difference in the latitude direction is EarthRadius * latitude difference
    • The distance difference in the longitude direction is EarthRadius * longitude difference * cos(latitude). We multiply by cos(lat) because the longitude degrees don't make the same km distance if the latitude changes. As P1 and P2 are close, cos(latP1) is close from cos(latP2)
    • Then Pythagore

    In JavaScript :

    function ClosePointsDistance(latP1, lngP1, latP2, lngP2) {
        var d2r = Math.PI / 180,
        R=6371; // Earth Radius in km
        latP1 *= d2r; lngP1 *= d2r; latP2 *= d2r; lngP2 *= d2r; // convert to radians
        dlat = latP2 - latP1,
        dlng = (lngP2 - lngP1) * Math.cos(latP1);
        return R * Math.sqrt( dlat*dlat + dlng*dlng );
    }
    

    I tested it between Paris and Orleans (France) : the formula finds 110.9 km whereas the (exact) Haversine formula finds 111.0 km.

    !!! Beware of situations around the meridian 0 (you may shift it) : if P1 is at Lng 359 and P2 is at Lng 0, the function will consider them abnormally far !!!

    0 讨论(0)
提交回复
热议问题