Check if Point is inside a Polygon using SQL

Using the geospatial SQL functions you can check if a point (with a given X,Y) is included inside a polygon

Example:

Declare @point geometry
Declare @polygon geometry
SET @point = geometry::STGeomFromText('POINT (-88.22 41.50000001)', 4326)
SET @polygon = geometry::STGeomFromText('POLYGON ((-88.2 41.5, -88.2 41.6, -88.3 41.6, -88.3 41.5, -88.2 41.5))', 4326)--124
Select @point.STIntersection(@polygon).ToString()  

This SQL code defines two geometry objects, @point and @polygon, and checks if they intersect.

The first two lines of the code declare the @point and @polygon variables as geometry data types. These variables are used to store the geometry objects for the point and polygon, respectively.

The SET statements create the geometry objects for the point and polygon. The geometry::STGeomFromText function is used to create the geometry objects from text representations. The first argument of this function is the text representation of the geometry, and the second argument is the spatial reference identifier (SRID) for the geometry. In this case, the SRID is 4326, which is the identifier for the WGS84 coordinate system.

The @point variable is set to a point geometry with the coordinates (-88.22, 41.50000001), and the @polygon variable is set to a polygon geometry with the specified vertices (-88.2 41.5, -88.2 41.6, -88.3 41.6, -88.3 41.5, -88.2 41.5).

The STIntersection method is then used to check if the point and polygon intersect. This method returns a geometry object representing the intersection of the two input geometries. If the two geometries do not intersect, the STIntersection method returns an empty geometry object.

The final line of the code calls the ToString method on the result of the STIntersection method, which returns the text representation of the resulting geometry object. In this case, if the point and polygon intersect, the result will be a POINT geometry object representing the intersection point. If they do not intersect, the result will be an empty geometry object.

Result

POINT (-88.220000000670552 41.500000009313226)

 

Post a Comment

Previous Post Next Post