w3resource

Assess Whether a Point Lies Within a Defined Area


Check if a Point is Within a Polygon

Write a MySQL query to verify if a given point lies inside a specified polygon using ST_Within.

Solution:

-- Check if a specific point is located within a defined polygon.
SELECT 

    -- Use the ST_Within function to determine whether the given POINT geometry 
    -- is contained within the specified POLYGON geometry. The result is returned as 'isWithin'.
    ST_Within(
        ST_GeomFromText('POINT(-73.97 40.78)'),  -- Define the POINT geometry to check.
        ST_GeomFromText('POLYGON((-73.99 40.77, -73.95 40.77, -73.95 40.79, -73.99 40.79, -73.99 40.77))')  -- Define the POLYGON geometry.
    ) AS isWithin;

Explanation:

  • Purpose of the Query:
    • The goal is to determine whether a point is located within a polygon.
    • This demonstrates the ST_Within function for spatial containment tests.
  • Key Components:
    • ST_Within(point, polygon) : Returns 1 (true) if the point is inside the polygon.
    • Well-Known Text (WKT) format is used to define the point and polygon.
  • Real-World Application:
    • Useful for geofencing applications and spatial queries based on regions.

Notes:

  • Ensure both geometries share the same spatial reference system.

For more Practice: Solve these Related Problems:

  • Write a MySQL query to check if a given point is inside a polygon stored in the "Regions" table using ST_Within.
  • Write a MySQL query to determine if a point generated by ST_GeomFromText falls within a dynamically defined polygon and return a boolean result.
  • Write a MySQL query to verify containment of a point in the "Boundaries" table using ST_Within, aliasing the result as "inside".
  • Write a MySQL query to filter records from "Zones" where a provided point lies within the polygon area stored in a spatial column.

Go to:


PREV : Find Locations Within a Radius.
NEXT : Create a Spatial Index on a Column.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.