Baz
Baz

Reputation: 13123

Distance outside shapely.Polygon

How do I establish the distance a point is from a polygon? If the point is within the polygon the result should be 0.

I'm guessing something like:

def distance_from(poly,point):
  if poly.contains(point): return 0 
  return poly.exterior.distance(point)

Upvotes: 2

Views: 4996

Answers (1)

phloose
phloose

Reputation: 141

I'd like to clarify things up a bit:

The instances which are passed to the distance_from function are made of the classes shapely.geometry.polygon.Polygon and shapely.geometry.point.Point from the shapely.geometry module of the Shapely Python package for computational geometry. (For more info on shapely and geometric objects have a look in the manual : Shapely Python Package, Geometric Objects).

The distance method of a geometric object returns the minimum float distance to another geometric object as described here in the manual. The exterior of a polygon is an instance of shapely.geometry.polygon.LinearRing which makes up the boundary of a polygon (although it is not to be mixed up with the boundary attribute of a polygon which returns a LineString). So for the case above you don't need to to explicitly use poly.exterior.distance(point) because the minimum distance is the same for the whole polygon as it is for its boundary. They have exactly the same shape only a different geometry type.

It would be less error prone if you would just use poly.distance(point) because that way if the point of interest lies within the interior (more info here) of the polygon it is directly clear that it contains it, so you do not need an explicit check and also the distance from a point within the interior to itself is then 0. It would be different if you would try to get the distance from the exterior (which, as explained above, is a LinearRing, i.e. a closed LineString) to a point which lies in the "inner" part. In this case you would get the minimum distance between the point in the "inner" part and the surrounding linear ring.

For further info about binary relationships (i.e between a geometric object and another, which covers contains, within, touches etc.) refer to this part of the manual and for those interested in the underlying DE-9IM relationships (which are a way to clearly identify the way a geometric objects relates to another) refer to this part.

Shapely is a python wrapper for the GEOS suite which itself is a C++ port of JTS. On the JTS page under the link Feature sheet more information can be found about how spatial relationships are checked and computed

Upvotes: 4

Related Questions