Spatial Operators

Understand the details of spatial operators in MySQL.

In the context of our e-scooter startup, we’ve accumulated various types of spatial data. This includes simple location points indicating where our e-scooters are stationed and more complex polygons defining the parking zones for these scooters. These data elements are essential in managing our daily operations and form the foundation for more advanced spatial analyses.

MySQL offers a set of specialized tools known as spatial operators. These operators empower us to perform calculations and derive additional spatial insights from the data gathered through our business operations.

The ST_Intersection() function

One important type of spatial entity in our dataset is the POLYGON. We use this geometric entity to define parking zones for our customers. To analyze these polygons, we use a function called ST_Intersection(). It calculates the intersection between two POLYGON or other geometries, such as points or lines. Passing two geometries as arguments, ST_Intersection() returns a new geometry of the same type (or a container of that type) within the same spatial reference system (SRS) that denotes the intersection between the two given geometries, if any. For example, let us consider the following two polygons:

Press + to interact
Two polygons in blue and green in a coordinate system
Two polygons in blue and green in a coordinate system

They can be represented in MySQL as POLYGON((1 1, 3 1, 3 0, 1 0, 1 1)) (refer to the blue rectangle) and POLYGON((2 1, 4 1, 4 0, 2 0, 2 1)) (refer to the green rectangle). Computing their intersection is possible using ST_Intersection(), providing the two polygons as arguments:

Press + to interact
-- Compute the intersection of two polygons
SELECT ST_AsText(ST_Intersection(ST_PolygonFromText('POLYGON((1 1, 3 1, 3 0, 1 0, 1 1))'),
ST_PolygonFromText('POLYGON((2 1, 4 1, 4 0, 2 0, 2 1))'))) AS Intersection;

In the above snippet, we create two geometries of the described polygons using ST_PolygonFromText() and input these two into ST_Intersection(). Finally, we convert the result to a ...

Access this course and 1400+ top-rated courses and projects.