Shapely – How to Measure Distance Using Shapely in Python

fionaogrpyqgispythonshapely

Reading the documentation…it looks like I should have this right, but I don't.

The example is:

Point(0,0).distance(Point(1,1))

1.4142135623730951

Based on this example I wrote this block (..note: update, 'capital' starts as a shapely obj, and city_pt is a dict…full of multipoints it appears, looking like this).

[{'geometry': {'type': 'MultiPoint',
'coordinates': [(4942585.391221348, #3940520.723517349)]},
'type': 'Feature', 'id': '17', 'properties':
OrderedDict([(u'Status', u'Bad')])}]

    # capital = shapely obj
    capital_pt = capital.coords
    # city_point is a dict ... multipoints
    for city_point in filtered_all:
        city_items = shape(city_point['geometry'])
        # capital_pt = POINT (13531245.47570414 2886003.268927813) 
        # city_items[0] = POINT (4942585.391221348 3940520.723517349)

        # measure distance

        # calculate the distance between capital and cities
        distance_between_pts = capital_pt.distance(city_point)

and got this:

AttributeError: 'CoordinateSequence' object has no attribute 'distance'

trying the om_henners answer I get

AttributeError: 'dict' object has no attribute 'coords'

Just in terminal I tried this:

x = POINT (13531245.47570414 2886003.268927813).distance(POINT (4942585.391221348 3940520.723517349))

File "", line 1
x = POINT (13531245.47570414 2886003.268927813).distance(POINT (4942585.391221348 3940520.723517349))
^
SyntaxError: invalid syntax

Best Answer

Your capital_pt is the coords attribute of the original capital shapely geometry object. In itself this is not a shapely geometry, rather a sequence of tuples of flots which are the point objects. Instead you should be using

distance_between_pts = capital.distance(city_items)

Given your case where you're trying to calculate distances for all points in a dataset opened by fiona, a quick example might help also:

import fiona
import shapely.geometry

# capital is a shapely geometry object

with fiona.open(path_to_data) as src:
    for feature in src:
        geom = shapely.geometry.shape(feature["geometry"])
        distance_between_pts = capital.distance(geom)
        print(distance_between_pts)