The data I've loaded from a shapefile into a geometry column in SQL Server (using NetTopologySuite) is not producing valid GeoJSON when I export it because it doesn't follow the right-hand rule.
I thought this would be easy to fix with the MakeValid()
function, but it's not correcting the issue.
I tried with a simplified geometry as below:
declare @geom geometry
select @geom = geometry::STGeomFromText('POLYGON ((
0 0,
0 1,
2 1,
2 0,
0 0
))', 4326)
select @geom, @geom.IsValidDetailed()
SQL Server says it's valid (24400: Valid), so presumably that's why it's not fixing it in the MakeValid
function.
What's the best way to resolve this? I've seen an option to use:
UPDATE table SET geom = geom.STUnion(geom.STStartPoint())
which works for simple polygons, but I'm not sure how well it will work for more complex geometries.
2 Answers 2
I've started working with NetTopologySuite, and have the same problem. I found a fix here. Simply put:
if (!polygon.Shell.IsCCW) polygon = polygon.Reverse();
If you have Geometries you will need to cast, and if you have MultiPolygons you will have to iterate through each of them.
-
Thanks! This worked for me!MBentley– MBentley2021年06月09日 21:39:26 +00:00Commented Jun 9, 2021 at 21:39
I had thought I would fix this in Sql Server using a spatial function like MakeValid
, but as that didn't work, I've found a way to fix it when loading the data from the shape file, using NetTopologySuite.
I was using:
var factory = new GeometryFactory();
using (var shapeFileDataReader = new ShapefileDataReader(filePath, factory))
But simply changing the factory worked, like this:
var factory = new OgcCompliantGeometryFactory();
using (var shapeFileDataReader = new ShapefileDataReader(filePath, factory))
Explore related questions
See similar questions with these tags.
MakeValid
is supposed to fix. So I'm wondering if there's something wrong with how I'm doing it, rather than looking for a new tool.