Side Determination of Points on Polylines Using 3D Cross Product
“Is this point to the left or to the right of my path?” Or a more intuitive situation: Is the address point to the left or right of the street? This post explores how to solve this using the 3D cross product with NumPy and Shapely libraries.
1. The Core Problem: Side Determination
When moving along a directed line from point
- Left Side: A counter-clockwise turn is needed to face the point.
- Right Side: A clockwise turn is needed to face the point.
- Collinear: The point lies exactly on the line (or its infinite extension).
To solve this mathematically, we treat the segments as vectors. Let
2. The Math: The 3D Cross Product
While the cross product is natively a 3D operation, it is the perfect tool for 2D side determination.
Geometric Definition
The 3D cross product (
The Right-Hand Rule
The direction of this
- If your fingers curl from
to and your thumb points Up ( ), the point is to the Left. - If your thumb points Down (
), the point is to the Right.
Algebraic Formula
For 2D vectors extended to 3D, the calculation simplifies significantly:
3. Applied Scenario: Path Following
In a real-world application, we don’t just have a single segment; we have a Polyline (
- Find the Nearest Point (
): Locate the point on the polyline closest to our target (using Shapely’s projectmethod). - Establish Direction (
): * Normal Case: Walk forward along the polyline from to find point . - Endpoint Case: If
is the end of the line, walk backward to find a point . To maintain a consistent forward-facing vector, we swap them: let the original be and the new be .
- Endpoint Case: If
- Construct Vectors: Define
and .
4. Implementation: NumPy & Shapely
Using Shapely for linear referencing and NumPy for the vector math allows for concise, readable code. We use an epsilon threshold to account for floating-point inaccuracies.
1 | import numpy as np |