w3resource

Identify Points Inside a Defined Bounding Box


Find Locations within a Bounding Box

Write a MySQL query to find all locations that fall within a specified bounding box using the MBRContains function.

Solution:

-- Retrieve locations from the Locations table that are within a defined bounding box.
SELECT 

    -- Select the 'name' column to display the name of the location.
    name

-- Retrieve data from the Locations table.
FROM Locations

    -- Use the MBRContains function to check if the 'location' column (a POINT) is contained within 
    -- the bounding box defined by the specified POLYGON. Only rows where the condition is true are returned.
    WHERE MBRContains(
        ST_GeomFromText('POLYGON((-74 40, -74 41, -73 41, -73 40, -74 40))'),  -- Define the bounding box as a POLYGON.
        location  -- Check if the 'location' column falls within this bounding box.
    );

Explanation:

  • Purpose of the Query:
    • The goal is to filter records based on whether they lie within a rectangular bounding box.
    • This demonstrates using MBRContains to perform fast spatial bounding box queries.
  • Key Components:
    • MBRContains(geometry, location) : Checks if the bounding box contains the point.
  • Real-World Application:
    • Common in map applications for quickly narrowing down geographic data.

Notes:

  • The bounding box is defined in WKT; ensure coordinates match your spatial data’s SRID.

For more Practice: Solve these Related Problems:

  • Write a MySQL query to retrieve all records from the "Locations" table where the spatial point lies within a specified bounding box using MBRContains.
  • Write a MySQL query to select all points from "GeoLocations" that fall inside a rectangular area defined by a polygon using MBRContains.
  • Write a MySQL query to filter records in "MapPoints" based on whether their spatial data is contained within a bounding box defined by ST_GeomFromText and MBRContains.
  • Write a MySQL query to identify locations in the "Locations" table that are within a user-specified bounding box using MBRContains.

Go to:


PREV : Insert a Point with a Specific SRID.
NEXT : Retrieve the SRID of a Geometry.

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.