3

I have polygon that I'm getting from external source. The polygon is not valid.

In [36]: p
Out[36]: <Polygon object at 0x7fec6bea6ac0>

In [37]: p.valid
[12/Dec/2017 19:13:19] WARNING [django.contrib.gis:85] GEOS_NOTICE: Hole lies outside shell at or near point 260561.40600000042 776052

I know that I can fix the polygon in the DB using the MakeValid() django function.

Is there a way to fix the polygon before it is inserted to the DB, just using geos API?

Thanks.

eran
  • 6,731
  • 6
  • 35
  • 52
  • I think you're misconstruing using a db function with a data update. Using `MakeValid` doesn't update the actual record itself until you explicitly call save. – Jason Dec 12 '17 at 23:44
  • thanks. I know. The problem I has is that the polygon itself is currently not in the DB. – eran Dec 14 '17 at 10:13
  • 1
    I feel you should be able to use that function without requiring a db value, as long as the polygon is in WKT or other postgis format. eg `SELECT ST_MAKEVALID(POLYGON('WKT text here'));` – Jason Dec 14 '17 at 13:58

2 Answers2

3

I don't know that this will fix your hole error necessarily, but I have had luck eliminating self-intersecting geoms by performing a 0-width buffer:

p = p.buffer(0)
0

The ST_MakeValid function is unfortunately not using a geos function, but is a custom function in PostGIS' own liblwgeom library.

I am not aware of any python bindings for liblwgeom, so if you want to call that function, you would have to do your own binding with ctypes. See this similar question for inspiration.

But if any method is good enough, I was also successful just using buffer(0), as suggested by in spatialbits' answer.

Chronial
  • 66,706
  • 14
  • 93
  • 99