mattijn / topojson

Encode spatial data as topology in Python! 🌍 https://mattijn.github.io/topojson
BSD 3-Clause "New" or "Revised" License
178 stars 27 forks source link

serialize_as_geojson outputs invalid GeoJSON #214

Closed Zaczero closed 7 months ago

Zaczero commented 9 months ago

I have noticed that geometry produced by serialize_as_geojson is not always valid. Essentially, a PostGIS server logged information like:

NOTICE:  Self-intersection at or near point -1.7646430670616482 43.343036981578791
NOTICE:  Self-intersection at or near point -56.757341551608846 -27.571978182790648
NOTICE:  Self-intersection at or near point -58.109818573194246 -33.009761116125937
NOTICE:  Self-intersection at or near point -56.792214220247686 -27.572121122268854
NOTICE:  Self-intersection at or near point 6.1868958925049995 50.640692266757227
NOTICE:  Self-intersection at or near point 6.1907987161590761 50.663999944400551

which made me investigate. I then confirmed the issue by checking:

shape(wkt_string).is_valid

where wkt_string is:

wkt.txt

I am using the following configuration:

tp.Topology(countries_geoms, prequantize=False)
topo.toposimplify(q, inplace=True)
features = serialize_as_geojson(topo.to_dict())['features']
Zaczero commented 9 months ago

A dirty fix would be just to apply:

orient(shape(feature['geometry']).buffer(0))

(which I am doing at the moment)

mattijn commented 7 months ago

there is also a validate argument as option within serialize_as_geojson(.., validate=True). See here what it is doing:

https://github.com/mattijn/topojson/blob/main/topojson/utils.py#L533

geom = shape(geom_map).buffer(0)

And documented here too: https://mattijn.github.io/topojson/example/output-types.html#to_geojson