6

I'm using GeoDjango with PostGIS and trying to use a polygon to get records from a database which fall inside it.

If I define a polygon which is bigger than half the area of the earth it assumes the 'inside' of my polygon is the smaller area which I intended as the 'outside' and returns only results which are outside it.

I can just use this smaller, wrong area to exclude results. Polygon.area seems to know what I intend so I can use this to determine when to make my search inclusive or exclusive. I feel like this problem is probably common, is there a better way to solve it?

Update: If 180 degrees longitude is inside my polygon this doesn't work at all. It seems GEOS is to blame this time. This image shows what I believe is the reason. Green is the polygon I define, Red is how it seems to be interpreting it.Polygons on earth Again this seems like a problem which would crop up often and one that libraries like GEOS are made to deal with. Is there a way?

Jake
  • 12,713
  • 18
  • 66
  • 96
  • Just FYI, this is intentional, though unexpected. Here's the documentation: http://postgis.net/docs/using_postgis_dbmanagement.html. Relevant excerpt: What is the longest arc you can process? We use great circle arcs as the "interpolation line" between two points. That means any two points are actually joined up two ways, depending on which direction you travel along the great circle. All our code assumes that the points are joined by the *shorter* of the two paths along the great circle. As a consequence, shapes that have arcs of more than 180 degrees will not be correctly modelled. – hirowatari May 12 '20 at 17:13

1 Answers1

6

Alright, no answers. Here's what I've done.

Because GEOS doesn't like things crossing the 180th meridian:
First check if the polygon crosses the 180th meridian - If so, break it into 2 polygons along that line.

Because PostGIS assumes a polygon is as small as possible you can't make one cover more than half the world, so:
Check if the polygon or each of the split polygons covers half the world or more - If so, break them in half.

Construct a MultiPolygon from the results.

Jake
  • 12,713
  • 18
  • 66
  • 96
  • Hi, I'm having the same original problem. What's a good way to split a polygon into the two sides? I'm trying `ST_Intersects` but I don't know what shape to use for the other argument. – Edmund Feb 16 '17 at 04:14
  • Hi @Edmund, my polygons were always 'rectangular', defined by top-left and bottom-right coordinates. It was easy to calculate the extent of two halves. Sorry I can't help with your situation. – Jake Feb 16 '17 at 22:23
  • Thanks Jake, I think I've figured out something that seems to work. Mine are sometimes rectangle too and I think the fact that the edges are on great circles (for geography type) makes things a bit less than obvious when it comes to finding the midpoint between two lines -- so I just intersect it with a polygon covering the west or east hemisphere. – Edmund Feb 19 '17 at 01:58