Update:
I changed the polygon as suggested, and I now get a LineString instead of a MultiLine string, but the difference in coordinates are still the same:
I'm comparing two libraries for working with spatial data, but they are giving me quite different results for the same input.
Here is a test using Microsoft.SqlServer.Types library
// Line from New York to Paris
SqlGeography line = SqlGeography.STLineFromText(new System.Data.SqlTypes.SqlChars("LINESTRING(-73.935242 40.730610, 2.349014 48.864716)"), 4326);
// Polygon in the Atlantic
SqlGeography polygon = SqlGeography.STPolyFromText(new System.Data.SqlTypes.SqlChars("POLYGON((-40 60, -40 30, -20 30, -20 60, -40 60))"), 4326);
SqlGeography intersection = line.STIntersection(polygon);
{LINESTRING (-19.99999999999997 52.21038270929611, -39.99999999999993 51.451383473748834)}
Here is a test with the NetTopologySuite:
var polygonText = "POLYGON((-40 60, -40 30, -20 30, -20 60, -40 60))";
string lineText = "LINESTRING(-73.935242 40.730610, 2.349014 48.864716)";
var rdr = new NetTopologySuite.IO.WKTReader();
var geometryPolygon = rdr.Read(polygonText);
var geometryLine = rdr.Read(lineText);
var polygon = _geometryFactory.CreatePolygon(geometryPolygon.Coordinates);
var line = _geometryFactory.CreateLineString(geometryLine.Coordinates);
var intersects = line.Intersection(polygon);
{LINESTRING (-40 44.34908739019244, -20 46.48166531033365)}
Any idea why there is such a large difference in the result?
The problem is that NetTopologySuite only performs planar 2d geometry operations.
SqlServer's geography
type performs geodesic operations within computation of distances and/or other spatial operations.
If you use SqlServer's geometry
type you should be getting -more or less- the same results.