Lines in the database

The first section of this chapter focused on point operations. Now, we will turn our attention to lines. For the following examples, you will create a new table and insert three lines. The following code will accomplish that:

from shapely.geometry import LineString
from shapely.geometry import MultiLineString

connection = psycopg2.connect(database="pythonspatial",user="postgres",
password="postgres")

cursor = c.cursor()
cursor.execute("CREATE TABLE lines (id SERIAL PRIMARY KEY, location GEOMETRY)")
thelines=[]
thelines.append(LineString([(-106.635585,35.086972),(-106.621294,35.124997)]))
thelines.append(LineString([(-106.498309,35.140108),(-106.497010,35.069488)]))
thelines.append(LineString([(-106.663878,35.106459),(-106.586506,35.103979)]))

mls=MultiLineString([((-106.635585,35.086972),(-106.621294,35.124997)),((-106.498309,35.140108),(-106.497010,35.069488)),((-106.663878,35.106459),(-106.586506,35.103979))])

for a in thelines:
cursor.execute("INSERT INTO lines (location) VALUES
(ST_GeomFromText('{}'))".format(a.wkt))
connection.commit()

The previous code should be familiar. It starts by connecting to the Python spatial database, gets a cursor, and then creates a table with an id and a location of the geometry type. You should import shapely LineString and MultiLineMultiline is so you can print the lines in the Jupyter notebook. You should create an array of lines and then loop through them, inserting each into the table using the cursor. You can then commit() the changes.

To see that the lines have been added to the database, you can execute the following code:

cursor.execute("SELECT id, ST_AsTexT(location) from lines")
data=cursor.fetchall()
data

The previous code executes a basic select statement on the new table. There should be three records in the result set, as follows:

[(1, 'LINESTRING(-106.635585 35.086972,-106.621294 35.124997)'),
(2, 'LINESTRING(-106.498309 35.140108,-106.49701 35.069488)'),
(3, 'LINESTRING(-106.663878 35.106459,-106.586506 35.103979)')]

If you print the mls variable (the variable holding a multilinestring in the earlier code) you can see the lines which are shown in the following image:

Now that you have a database table with a few lines, you can proceed to measure them and find out if they intersect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset