Patricio
Patricio

Reputation: 137

How to calculate distance between lat/long in c#

In a c# winform application I've a latitude/longitude List. I can to calculate in sql server (2005) query but I dont know if I can do this in c#.

SELECT LAT, LONG, ( 3959 * acos( cos( radians(37) ) * cos( radians( LAT ) ) * cos( radians( LONG ) - radians(-122) ) + sin( radians(37) ) * sin( radians( LAT ) ) ) ) AS distance
FROM Table ORDER BY distance

Using This query in sql server I can order a list of latitude and longitude. But, in c# I've lat/long in this list:

var latLon = new List<LatLonClass>();

Using this list, How can I do same query in my List? Thanks!

Upvotes: 0

Views: 4775

Answers (3)

Eser
Eser

Reputation: 12546

Just see the System.Device.Location namespace.

var coord1 = new GeoCoordinate(lat1, lon1);
var coord2 = new GeoCoordinate(lat2, lon2);

var dist = coord1.GetDistanceTo(coord2);

For more info: https://msdn.microsoft.com/en-us/library/system.device.location.geocoordinate(v=vs.110).aspx

Now, to calculate distances of a list of cordinates to a single point

List<GeoCoordinate> coordinates = ......;
GeoCoordinate point = ......;

var distances = coordinates.Select(c => c.GetDistanceTo(point))
                           .OrderBy()
                           .ToList();

Upvotes: 4

Kuba Szostak
Kuba Szostak

Reputation: 472

It depends on how accurate results you need. Our earth isn't sphere, it is ellipsoid (one can say radius is between 6378137m and 6356752m) . Thats why for accurate result you need to know math on very adwanced level. If you need more precision than 0.3% I suggest you use Charles Karney's GeographicLib - http://geographiclib.sourceforge.net/html/NET/

If precision at 0.3% level is enough for you use @Mark code.

Upvotes: 1

Mark
Mark

Reputation: 4883

Here is a snippet from the Haversine formula, found (https://www.stormconsultancy.co.uk/blog/development/code-snippets/the-haversine-formula-in-c-and-sql/). Looks like it has what you need.

public double HaversineDistance(LatLng pos1, LatLng pos2, DistanceUnit unit)
{
    double R = (unit == DistanceUnit.Miles) ? 3960 : 6371;
    var lat = (pos2.Latitude - pos1.Latitude).ToRadians();
    var lng = (pos2.Longitude - pos1.Longitude).ToRadians();
    var h1 = Math.Sin(lat / 2) * Math.Sin(lat / 2) +
                  Math.Cos(pos1.Latitude.ToRadians()) * Math.Cos(pos2.Latitude.ToRadians()) *
                  Math.Sin(lng / 2) * Math.Sin(lng / 2);
    var h2 = 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
    return R * h2;
}

Upvotes: 3

Related Questions