19

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!

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked May 12, 2014 at 13:26

2 Answers 2

22

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.

answered May 12, 2014 at 16:38
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? Commented May 13, 2014 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. Commented May 13, 2014 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. Commented May 13, 2014 at 14:25
  • Check, it works now; thanks (again) for the speedy followup! Commented May 13, 2014 at 14:43
7

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[:])
ojdo
4581 gold badge3 silver badges11 bronze badges
answered May 12, 2014 at 15:15
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.