Monday 23 December 2019

How to use SpatiaLite functions in a Python script?


I'm trying to find the intersection coordinates between a line (knowing its start and end points) and a polygon (SQlite file).


I've managed to make it work in QGIS by creating a shapefile for the line and then using DBmanager and the following SQL statement:


SELECT astext(st_intersection(polygon.geom, line.geom)) as XY

from polygon, line
WHERE st_intersects(polygon.geom, line.geom)

It works just fine but now I'm trying to make it work in a python script with the XY coordinates of the line and the polygon.sqlite file as inputs.


I'm trying to write the code and I've come to this so far:


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import gdal
import ogr

import sqlite3
import math
import shapefile
import pyspatialite



fichier=open("C:\\MyPath\\polygon.sqlite","r")
connR =sqlite3.connect("C:\\MyPath\\polygon.sqlite")


curR =connR.cursor()

#trying to add a table for the line:

curR.execute("""
CREATE TABLE my_line(
id INTEGER PRIMARY KEY,
XMin INTEGER,
YMin INTEGER,
XMax INTEGER,

YMax INTEGER,
geom MULTILINESTRING
)
""")
connR.commit

# user coordinates inputs

XA=input('X A = ');
YA=input('Y A = ');

XB=input('X B = ');
YB=input('Y B = ');

curR.execute("""INSERT INTO route VALUES (?,?,?,?,?,?)""", (1, XA, YA, XB, YB,"MULTILINESTRING"))
connR.commit()

#trying to use SpatiaLite functions:

curR.execute("""
SELECT astext(st_intersection(polygon.geom, line.geom)) as XY

from polygon, line
WHERE st_intersects(polygon.geom, line.geom)
""")
connR.commit()

As you can see, my first problem is that I don't know how to create a "line" object in the table 'my_line'. My second problem is that I don't know how to use the SpatiaLite functions in a python script.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...