CriosR
CriosR

Reputation:

Distance between 2 geocodes

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, I'm not on 08 yet. Any help would be appreciated.

Upvotes: 5

Views: 15866

Answers (9)

user1032317
user1032317

Reputation:

Here is a way to do it if you are using sql server.

CREATE function dist (@Lat1 varchar(50), @Lng1 varchar(50),@Lat2 varchar(50), @Lng2 varchar(50)) 
returns float 
as
begin

declare @p1 geography
declare @p2 geography

set @p1 = geography::STGeomFromText('POINT('+ @Lng1+' '+ @Lat1 +')', 4326)
set @p2 = geography::STGeomFromText('POINT('+ @Lng2+' '+ @Lat2 +')', 4326)

return @p1.STDistance(@p2)
end

Upvotes: 1

Myobis
Myobis

Reputation: 1357

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 !!!

Upvotes: 2

Mr Harno
Mr Harno

Reputation: 318

This will do it for you in c#.

Within the namespace put these:

 public enum DistanceType { Miles, Kilometers };

public struct Position
{
    public double Latitude;
    public double Longitude;
}

class Haversine
{

    public double Distance(Position pos1, Position pos2, DistanceType type)
    {
        double preDlat = pos2.Latitude - pos1.Latitude;
        double preDlon = pos2.Longitude - pos1.Longitude;
        double R = (type == DistanceType.Miles) ? 3960 : 6371;
        double dLat = this.toRadian(preDlat);
        double dLon = this.toRadian(preDlon);
        double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
        Math.Cos(this.toRadian(pos1.Latitude)) * Math.Cos(this.toRadian(pos2.Latitude)) *
        Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
        double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
        double d = R * c;
        return d;
    }

    private double toRadian(double val)
    {
        return (Math.PI / 180) * val;
    }

Then to utilise these in the main code:

Position pos1 = new Position();
                    pos1.Latitude = Convert.ToDouble(hotelx.latitude);
                    pos1.Longitude = Convert.ToDouble(hotelx.longitude);
                    Position pos2 = new Position();
                    pos2.Latitude = Convert.ToDouble(lat);
                    pos2.Longitude = Convert.ToDouble(lng);
                    Haversine calc = new Haversine();

                    double result = calc.Distance(pos1, pos2, DistanceType.Miles);

Upvotes: 2

Edward Kmett
Edward Kmett

Reputation: 29962

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

Upvotes: 1

pipTheGeek
pipTheGeek

Reputation: 2713

Sorry, I don't know what country you are in even. Are we talking about Easting and Northings (UK, Ordance Survey system) or Lat/Long or some other system? If we are talking Easting and Northing then you can use
sqr((x1-x2)^2 + (y1-y2)^2)
This does not allow for the fact that the earth is a sphere, but for short distances you won't notice. We use it at work for distances between points within the county.
Be carful about how longer grid reference you use. I think an 8 figure reference will give you a distance in metres. I'll be able to get a definate answer at work next week if no one else has supplied it.

Upvotes: 0

JMD
JMD

Reputation: 1408

Use an approximation of the earth and the Haversine formula. You can get a javascript version on the following url, which you can translate to your language of choice:

http://www.movable-type.co.uk/scripts/latlong.html

Here is another way: http://escience.anu.edu.au/project/04S2/SE/3DVOT/3DVOT/pHatTrack_Application/Source_code/pHatTrack/Converter.java

Upvotes: 8

taserian
taserian

Reputation: 623

You're looking for the length of the Great Circle Path between two points on a sphere. Try looking up "Great Circle Path" or "Great Circle Distance" on Google.

Upvotes: 0

SQLMenace
SQLMenace

Reputation: 134961

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

Upvotes: 2

happythenewsad
happythenewsad

Reputation: 1785

the pythagorean theorem?

Upvotes: -1

Related Questions