12

If have two points, from which I want to create a straight LineString object:

from shapely.geometry import Point, LineString
A = Point(0,0)
B = Point(1,1)

The Shapely manual for LineString states:

A sequence of Point instances is not a valid constructor parameter. A LineString is described by points, but is not composed of Point instances.

So if I have two points A and B, is there a shorter/better/easier way of creating a line AB than my current "best" guess...

AB = LineString(tuple(A.coords) + tuple(B.coords))

... which looks rather complicated. Is there an easier way?


With Shapely 1.3.2, the above statement from the manual is no longer correct. So from now on,

AB = LineString([A, B])

works!

12

Since Shapely 1.3, you can create a LineString from Points:

>>> from shapely.geometry import Point, LineString
>>> LineString([Point(0, 0), Point(1, 1)]).wkt
'LINESTRING (0 0, 1 1)'

Apologies for the contradiction in the manual.

4
  • On two machines (one Linux, one Windows), after upgrading to Shapely 1.3.1 (shapely.__version__ agrees) and pasting your code verbatim, I receive a ValueError from linestring.pyc#228 about "Input [<...Point object at 0x..>, <...Point object at 0x...>] is the wrong shape for a LineString". Have I missed something? – ojdo May 13 '14 at 11:12
  • Update: the corresponding pull request #102 is only in master, not yet merged to branch 1.3 and thus not present in the current 1.3.1 release. – ojdo May 13 '14 at 11:27
  • You're right. I've just now fixed this in github.com/Toblerity/Shapely/issues/130 and uploaded 1.3.2 to PyPI. – sgillies May 13 '14 at 14:25
  • Check, it works now; thanks (again) for the speedy followup! – ojdo May 13 '14 at 14:43
6

The base method is:

AB = LineString([(A.x,A.y), (B.x,B.y)])

You can also use slicing to concatenate the coordinate lists:

AB = LineString(A.coords[:] + B.coords[:])
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.