gdal icon indicating copy to clipboard operation
gdal copied to clipboard

Calling Distance on an empty geometry returns 0

Open jontwo opened this issue 3 months ago • 7 comments

What is the bug?

An empty geometry has a Distance to another geometry of 0; it would be better to raise an error, as this calculation is essentially undefined. For example, Python would would raise a TypeError if a user entered something like 1 > None .

Steps to reproduce the issue

Using the Python bindings:

line1=ogr.CreateGeometryFromWkt("LINESTRING EMPTY")
line2=ogr.CreateGeometryFromWkt("LINESTRING (0 0,5 5)")
line1.Distance(line2)

>>> 0.0

Versions and provenance

Reproduced on Windows 11, GDAL 3.9.0 (OSGeo4W) and Ubuntu 22.04, GDAL 3.8.5 (built from source).

Additional context

No response

jontwo avatar Aug 28 '25 10:08 jontwo

PostGIS gives NULL

select st_distance(
'linestring empty','LINESTRING (0 0,5 5)');

NULL also from ogrinfo when using SQLite dialect ogrinfo -dialect SQLite -sql "select st_distance(st_geomfromtext('linestring empty'),st_geomfromtext ('LINESTRING (0 0,5 5)'))" :memory:

jratike80 avatar Aug 28 '25 11:08 jratike80

That would also work for us. If None was returned and you then tried to check the distance was below a threshold, you'd get the TypeError mentioned above.

jontwo avatar Aug 28 '25 12:08 jontwo

This is a GEOS behavior that comes from https://github.com/libgeos/geos/blob/3bdeea5375b13c4f57da6e9e399b2c4e39540737/src/operation/distance/DistanceOp.cpp#L113 . @dbaston do you think it would makes more sense for that GEOS method to return +Infinity instead of 0 ?

rouault avatar Aug 30 '25 10:08 rouault

also CC'ing @dr-jts as I see this is a specified behavior of JTS in https://github.com/locationtech/jts/blame/2c85e142539b1832776d3792c32d88164e83e4fc/modules/core/src/main/java/org/locationtech/jts/operation/distance/DistanceOp.java#L151

rouault avatar Aug 30 '25 10:08 rouault

Doesn't PostGIS use GEOS as well? Why does it show null as distance instead of 0.0?

jratike80 avatar Aug 30 '25 10:08 jratike80

Doesn't PostGIS use GEOS as well?

I checked and it has its own implementation that doesn't use GEOSDistance

rouault avatar Aug 30 '25 10:08 rouault

I checked and it has its own implementation that doesn't use GEOSDistance

SpatiaLite seems to use GEOS https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html also but it returns NULL.

jratike80 avatar Aug 30 '25 15:08 jratike80

I checked and it has its own implementation that doesn't use GEOSDistance

SpatiaLite seems to use GEOS https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html also but it returns NULL.

on close inspection, Spatialite detects empty geometries before calling GEOS

Attempting to fix the issue in GEOS per https://github.com/libgeos/geos/pull/1345

rouault avatar Dec 16 '25 23:12 rouault