I have a problem I hope you guys can help me solve.
I have got a DbGeometry point (or DbGeography, I can use both) and I would like to check if this is within a DbGeometry Polygon (alternatively a DbGeography).
I am doing this at the moment:
var dbZones = new List<WasteManager.Database.Zone>();
foreach(var zone in zones)
{
var res = from z in DatabaseContext.Zones
let boundary =
!z.BoundaryGeometry.IsValid
? SqlSpatialFunctions.MakeValid(z.BoundaryGeometry)
: z.BoundaryGeometry
where z.ID == zone.ID && point.Within(boundary)
select z;
if(res.FirstOrDefault() != null) dbZones.Add(res.FirstOrDefault());
}
So I iterate through zones (EF entity of my db) and check if this point I have is within this boundary.
Problem is that it does not return any result, but I know that that point is within that boundary because I created manually the boundary and the point to be inside that boundary.
Can anyone tell me if what I am doing is wrong, if there is another way to do this or whatever else?
Much appreciate.
Manuel
It's quite easy actually.
I would like to add a comment to Nick Strupat.
You should be carefull with ring orientation. SQL Server uses left-handed orientation, which means that if you are walking along the perimeter of a polygon, your left hand should be on the inside of the polygon and your right hand on the outside (counter-clockwise or anti-clockwise). I got the “ring orientation” error because I drew my polygon in the opposite direction (clockwise, or right-handed) which meant that SQL Server was treating the whole surface of the earth EXCEPT FOR my polygon as the area of the polygon.
To check if a point is in the polygon you should always use
point.Intersects(polygon)
and not!point.Intersects(polygon)
.There is a solution to check if your polygon is ok or not by checking the size of the Area, For more information go to :
https://blog.falafel.com/ring-orientation-sql-spatial/
Here is my code based on the blog explanation :
I would also like to add a comment but to @BenoitGlaizette.
The code
polygon.Area.HasValue
can throw the following error for someMultipolygons
.However this won't occur if we convert to
SqlGeography
directly.For those that use Entity Framework 5<:
I use this extension method to check every
Polygon
andMultipolygon
before saving them to the database.I can then use a method like this to check
Intersects
at database level.T-SQL generated by Entity Framework:
Can be tested like this manually:
More information can be found here:
https://docs.microsoft.com/en-us/sql/t-sql/spatial-geometry/stintersects-geometry-data-type