Reputation: 2161
I have a set of latitude Longitude points. If I wanted to test if a new point was within x metres of any of the existing points would this be possible? Would it be best if I use this way?
ForEach(Coordinate coord in Coordinates)
{
var distance = GeoCoordinate.GetDistance(lat,lon);
if(distance <= x)
{
addToQualifyingList(coord);
}
}
and compare the new coordinate with every point in the set and check to see it is within x metres?
Upvotes: 1
Views: 2273
Reputation: 45947
Here is a method to calculate the distance between 2 points (lat1, lon1 and lat2, lon2)
public enum DistanceUnit { miles, kilometers, nauticalmiles }
public double GetDistance( double lat1, double lon1 , double lat2 , double lon2, DistanceUnit unit)
{
Func<double, double> deg2rad = deg => (deg * Math.PI / 180.0);
Func<double, double> rad2deg = rad => (rad / Math.PI * 180.0);
double theta = lon1 - lon2;
double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
dist = Math.Acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == DistanceUnit.kilometers)
{
dist = dist * 1.609344;
}
else if (unit == DistanceUnit.nauticalmiles)
{
dist = dist * 0.8684;
}
return (dist);
}
To determine all Coordinates with distance below 1 kilometer:
List<Coordinate> result = Coordinates.Where(x => GeoCoordinate.GetDistance(lat,lon, x.lan, x.lon, DistanceUnit.kilometers) < 1).ToList();
Upvotes: 2
Reputation: 214
Latitude and Longitude are both needed to know the position on earth or any other sphere shaped object. These are given in degree from their respective zero line / point.
http://www.movable-type.co.uk/scripts/latlong.html
Has a solution in Java
> var R = 6371e3; // metres
> var φ1 = lat1.toRadians();
> var φ2 = lat2.toRadians();
> var Δφ = (lat2-lat1).toRadians();
> var Δλ = (lon2-lon1).toRadians();
>
> var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
> Math.cos(φ1) * Math.cos(φ2) *
> Math.sin(Δλ/2) * Math.sin(Δλ/2);
> var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
>
> var d = R * c;
Apparently, this is this is one of the best solutions for small distances.
You should be able to just copy and paste it to C#, youll jsut have to change the variable names.
Upvotes: 0