# Finding out if two areas on the globe intersect

We present a one-line algorithm that tests for the intersection of two segments of a circle. We use this technique to check if two rectangular areas on the globe intersect. Although the problem is deviously bewildering, the algorithm is unbelievably simple. A stored SQL procedure implementation and a sample GIS SQL query illustrate the algorithm. The algorithm was derived on Fri, 28 Aug 1998 01:21:34 GMT.

## Introduction

Testing two "rectangular" areas on the globe for intersection is markedly more complicated than it may appear. The challenge comes from longitude's wrapping around, that is, abruptly jumping from 180 degrees (i.e., `180E` ) to -180 degrees when we cross the International Date Line. Latitudes do not wrap around. Therefore, in the body of this article, we concentrate on a one-dimensional problem of checking two segments of a circle for intersection. We will generalize to georectangles and geographical information systems in the last section.

To identify points on a circle, we will pick one point as the origin and will refer to the other points by their angular distance : "longitudes". The longitudes are measured in degrees, counter-clockwise (that is, "East-wise") from the point of origin. We will keep the longitudes within the range `[-180,180)` , by adding or subtracting 360 if necessary.

A segment `X` of a circle is specified by its left end, `LX` and its right end, `RX`. In other words, a segment `[LX, RX]` starts at the point `LX` and stretches counter-clockwise to the point `RX`. The coordinate -- longitude -- of the point `LX` may be less, equal or greater than that of the point `RX`. We assume that all segments are shorter than the full circle. We call two segments intersecting if one segment contains an internal point of the other.

## Examples of the problem

The following examples illustrate how non-obvious the intersection testing is.

Segment A Segment B Intersect?
`[1, 10]` `[15, 20]` NO
`[10, 1]` `[15, 20]` YES
`[5, 6]` `[4, 7]` YES
`[6, 5]` `[4, 7]` still YES
`[178, -178]` `[179, -179]` YES
`[-178, 178]` `[179, -179]` NO
`[178, -178]` `[-170, -100]` NO
`[-178, 178]` `[-170, -100]` YES

It is quite difficult to devise a single inequality involving `LA`, `LB`, `RA`, and `RB` that holds if and only if the segments intersect.

## The algorithm

Suppose we are given two segments: segment A `[LA, RA]` and segment B `[LB, RB]`. We assume that the longitudes, `LA`, `RA`, `LB`, and `RB`, are the numbers within [-180,180).

```     diff(`RA`-`LA`) + diff(`LB`-`RA`) + diff(`RB`-`LB`) + diff(`LA`-`RB`) = 360
<=> the segments do not intersect
```
where `diff(x) = x mod 360` normalizes `x` to be within [0,360); that is
```     diff(x) = x if x >= 0;
360+x otherwise
```

The algorithm is indeed that simple. We merely need to compute four sets of differences, adding 360 to make all of them positive. If these four numbers add to 360, the segments in question do NOT intersect.

## The proof of the algorithm

### Forward proof

The segments do not intersect => the sum is equal to 360.

Suppose `[LA, RA]` and `[LB, RB]` do not intersect. If we start at the point `LA` and walk to the East, we will encounter the following points

```     `LA`,`RA`,`LB`,`RB`, back to `LA`
```
in exactly that sequence. That means the segments `[LA, RA]` , `[RA, LB]`, `[LB, RB]` and `[RB, LA]` are all disjoint and together make up the full circle. The function `diff(x) ` is designed so that `diff(RX-LX) ` is the length of a segment `[LX, RX]`. The (angular) length is a number within [0,360). The sum `diff(RA-LA) + diff(LB-RA) + diff(RB-LB) + diff(LA-RB) ` is then the length of the full circle.

### Converse proof

The sum is equal to 360 => the segments do not intersect.

We will prove the second part of the correctness theorem by contradiction. Let us assume that the sum is equal to 360 but the segments still intersect. There are three major cases to consider: (i) segment B is entirely within segment A (or the other way around); (ii) Segment A contains `LB` but not `RB` ; (iii) Segment A contains both endpoints `LB` and `RB`, but not the whole `[LB, RB]`.

Case 1: Segment B is entirely within Segment A. If we walk from `LA` to the East we will pass the points `LB`, `RB`, `RA`, and come back to `LA`. Noting that `diff(-x) + diff(x) = 360` for `x > 0` , we write:

```     diff(`LB`-`RA`) = 360 - diff(`RA`-`LB`) = 360 - diff(`RB`-`LB`) - diff(`RA`-`RB`)
diff(`LA`-`RB`) = 360 - diff(`RB`-`LA`) = 360 - diff(`RB`-`LB`) - diff(`LB`-`LA`)
diff(`RA`-`LA`) = diff(`LB`-`LA`) + diff(`RB`-`LB`) + diff(`RA`-`RB`)
```
Thus we have
```     diff(`RA`-`LA`) + diff(`LB`-`RA`) + diff(`RB`-`LB`) + diff(`LA`-`RB`) = 720
```
which is contrary to our assumption that this sum is 360.

Case 2: Segment A contains `LB` but not `RB`. This implies that `RB` must be distinct from `LA` and `LB` must be distinct from `RA`. The same walk as in Case 1 gives us the following sequence of points: `LA`, `LB`, `RA`, `RB`, `LA`. Therefore

```     diff(`LA`-`RB`) = 360 - diff(`RB`-`LA`) = 360 - diff(`LB`-`LA`) - diff(`RA`-`LB`) - diff(`RB`-`RA`)
```
which means that the sum
```     diff(`RA`-`LA`) + diff(`LB`-`RA`) + diff(`RB`-`LB`) + diff(`LA`-`RB`) = 720
```
and not 360 as we assumed initially.

Case 3: Segment A contains both points `LB` and `RB`, but not all the points in between; for example: `[6, 5]` and `[4, 7]`. The walk to the East starting from `LA` goes through the points `LA`, `RB`, `LB`, `RA` and back to `LA`. Let us consider the equality

```     diff(`RB`-`LA`) + diff(`LB`-`RB`) + diff(`RA`-`LB`) + diff(`LA`-`RA`) = 360
```
The right-hand side of the equality looks almost the same as the sum we want to evaluate:
```     diff(`RA`-`LA`) + diff(`LB`-`RA`) + diff(`RB`-`LB`) + diff(`LA`-`RB`) ,
```
only all the differences are in "reverse": `diff(RA-LA) ` rather than `diff(LA-RA) ` , etc. Keeping in mind that `diff(x) = 360 - diff(-x) ` for `x > 0` , we obtain
```     diff(`RA`-`LA`) + diff(`LB`-`RA`) + diff(`RB`-`LB`) + diff(`LA`-`RB`) = 1080
```
if all four end points are distinct. If `LA` and `RB` are the same, the sum will be equal to 720. Ditto if `LB` and `RA` are the same. In any event, the result contradicts our initial assumption. Note: since we assumed that segments A and B intersect, one segment must contain an internal point of the other. This fact implies that `LA` and `RB` cannot be the same when `LB` and `RA` are the same.

QED.

## A sample application: GIS database queries

The intersection algorithm has been used in a production geographical information system. One of the databases stores satellite imagery. A satellite image is characterized, among other attributes, by its georectangular bounding box. A user can select an area of interest (again, as a georectangle) and find out relevant satellite images, i.e., the images whose bounding box intersects the area of interest. If the area of interest is a circle or a complex polygon, we can inscribe it into a georectangle and use the algorithm above. The test may in this case yield a false positive, but it will never return a false negative. Therefore, the georectangle intersection approach can be used as the first, winnowing stage in checking for intersection of complex areas on the globe.

The following is a query template excerpted from the production code. The query returns the bounding boxes and the descriptions of all satellite images that intersect a user-defined georectangle. The latter is specified by its two corner-points: `(NLAT, WLON)` and `(SLAT,ELON)` .

```     SELECT lat_n, lat_s, lon_w, lon_e, descr
FROM ImageDescr
WHERE
(SELECT image_descr FROM Timestamps) >= '2002-06-07 16:47'
AND lat_s <= 'NLAT' AND lat_n >= 'SLAT'
AND q_lon_intersect(lon_w,lon_e,WLON,ELON) <> 360
ORDER BY lat_n, lat_s, lon_w, lon_e
```

The query relies on the following stored procedure `q_lon_intersect()` , which implements the segment intersection algorithm verbatim:

```     -- This q_lon_intersect(lon_w,lon_e,Query_WLON,Query_ELON)
-- procedure determines if two circle segments [lon_w, lon_e] and
-- [Query_WLON, Query_ELON]  intersect. The procedure works correctly
-- for lon_w < lon_e and lon_w >= lon_e (and similarly for Query_WLON
-- and Query_ELON).
-- The two circle segments intersect when the result of this procedure
-- is NOT equal to 360.

CREATE PROCEDURE q_lon_intersect
(La SMALLFLOAT, Ra SMALLFLOAT, Lb SMALLFLOAT, Rb SMALLFLOAT)
returning SMALLFLOAT;
DEFINE d1, d2, d3, d4 SMALLFLOAT;
LET d1, d2, d3, d4 = Ra-La, Lb-Ra, Rb-Lb, La-Rb;
RETURN  CASE WHEN d1 < 0 THEN 360 + d1 ELSE d1 END +
CASE WHEN d2 < 0 THEN 360 + d2 ELSE d2 END +
CASE WHEN d3 < 0 THEN 360 + d3 ELSE d3 END +
CASE WHEN d4 < 0 THEN 360 + d4 ELSE d4 END;
END PROCEDURE
DOCUMENT 'Compute a SMALLFLOAT that can tell if two circle segments',
'intersect. If they do, the result of this procedure is',
'NOT equal to 360.'
WITH LISTING IN '/tmp/sql.complile.log';
```

### Last updated June 7, 2002

This site's top page is http://okmij.org/ftp/

oleg-at-okmij.org