I've got lots of flight data from glider pilots in the form of gps fixes in a fixed interval.
I would like to analyze the flight path and detect the start and the end of the 'circling' the glider pilot will do when he finds thermals.

Ideally, an algorithm would give me a start and an end point on the line, defining one "circle". These points could be equal to one of the gps fixes and do not need to be interpolated.

I simply could walk along the flight path, check the turn-rate and have some criteria to decide if the glider is circling or not.

As I am using PostgreSQL with PostGIS extension, I was curious if there is a better approach to this issue.
I already have an procedure to calculate the angle of two line segments:

```
CREATE OR REPLACE FUNCTION angle_between(
  _p1 GEOMETRY(PointZ,4326),
  _p2 GEOMETRY(PointZ,4326),
  _p3 GEOMETRY(PointZ,4326)
) RETURNS DECIMAL AS $$
DECLARE
  az1 FLOAT;
  az3 FLOAT;
BEGIN
  az1 = st_azimuth(_p2,_p1);
  az3 = st_azimuth(_p2,_p3);
IF az3 > az1 THEN
  RETURN (
      degrees(az3 - az1)::decimal - 180
  );
ELSE
  RETURN (
      degrees(az3 - az1)::decimal + 180
  );
END IF;
END;
$$ LANGUAGE plpgsql;

```

It should be possible to loop over all line segments and check, when the sum of the angles is greater than 360 or less than -360 degrees. Then I could use st\_centroid to detect the center of the circle, if needed.

Is there a better approach?

---

As requested, I uploaded an [example flight](https://www.dropbox.com/s/n9r07eny8ul8nbj/sample_flight.sql?dl=0).

[![A sample flight path](https://i.stack.imgur.com/oq90u.png)](https://i.stack.imgur.com/oq90u.png)