I need a function to calculate distance between point A and point B.
Namespace System.Spatial
seems to be exactly what I need, but I can't figure how to use it.
IPoint
is an interface that provides Latitude
and Longitude
, both of type double
.
First try :
public static double CalculateDistance(IPoint pointA, IPoint pointB)
{
var gp1 = GeographyPoint.Create(pointA.Latitude, pointA.Longitude);
var gp2 = GeographyPoint.Create(pointB.Latitude, pointB.Longitude);
return gp1.Distance(gp2) ?? 0;
}
That ends with a NotImplementedException
on point1.Distance(point2)
. The message is in french, but basically it says "No operation registered. Please provide operation using property SpatialImplementation.CurrentImplementation.Operations".
Ok, I will try this then :
public static double CalculateDistance(IPoint pointA, IPoint pointB)
{
var gp1 = GeographyPoint.Create(pointA.Latitude, pointA.Longitude);
var gp2 = GeographyPoint.Create(pointB.Latitude, pointB.Longitude);
return SpatialImplementation.CurrentImplementation.Operations.Distance(gp1, gp2);
}
Now I got a NullReferenceException
on SpatialImplementation.CurrentImplementation.Operations
.
Msdn is not much verbose about this.
Anyone can explain how to get these implementations ?
IMHO you shouldn't use System.Spatial
. It's an half-baked library created for OData interoperability with Spatial, namely for WCF Data-Services.
You can check here for more information. Also, most of the classes on that library are abstract, hence up-to-you to be implement most-of-it.
Also, and even worse, they're incompatible with Entity Framework spatial support.
I'm not sure what kind of project you're on but I would suggest these guidelines:
if you just need to calculate distances between points just copy an implementation of the Haversine Formula or Vincenty's Formula in C#.
if you need spatial on DB just go with Entity Framework 5/6.
if you need further spatial operations in c# use something like NetTopologySuite. There's a NuGet for it and it's really simple to use.