Thursday, 2 August 2018

Hyperlinking to PostGIS Layers and Zip files with QGIS Actions


I previously asked a question about hyperlinking data in QGIS that gets loaded into QGIS (see post: Hyperlinking in QGIS - Add Data to current window). A user provided me with the code, which works perfectly [Python qgis.utils.iface.addRasterLayer("C:\Users\Ryan Garnett\Dropbox\SpatialData\Imagery\Landsat\%Image")].



I am hoping to modify this code so that I can do two different actions: 1) Load data from a PostGIS Database 2) Have a zip file saved to a location on a local computer


I have data stored in a PostGIS database (ie: LUGDC as the Database, basedata as the Schema, bound_poly as the Table). In some instances there may be points, lines and polygons for the regon, so I am thinking of an Action for each of the geometry types.


With regards to the zip files, I have the files in a shared location, but I would like to have it so the file is copied from that location to a specified location on a local machine through an action.


Any help would be appreciated.


Thanks...



Answer



For the copy action you can use a action with Type:Windows and a Action of:


cmd /c copy {your file location} {dest}

e.g.



cmd /c copy C:\Temp\250mmContours.shp C:\

Will copy 250mmContours from C:\Temp to C:\


And for PostGIS have a action with Type:Python and Action text of:


uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "postgis", "{username}", "{your password}")
uri.setDataSource("public", "{layer}", "{geom column}", "")
qgis.utils.iface.addVectorLayer(uri.uri(), "layer_name_you_like", "postgres")

like so:



uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "postgis", "postgres", "xxxxxxxx")
uri.setDataSource("public", "signs", "the_geom", "")
qgis.utils.iface.addVectorLayer(uri.uri(), "layer_name_you_like", "postgres")

Obviously replacing any values you need with a expession inside [% {expression} %]


You can even do something like this to load the three layers at once:


def loadLayer(name):
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "postgis", "postgres", "xxxxx")

uri.setDataSource("public", name, "the_geom", "")
qgis.utils.iface.addVectorLayer(uri.uri(), name, "postgres")

loadLayer("layer1")
loadLayer("layer2")
loadLayer("layer3")

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...