Skip to content

Instantly share code, notes, and snippets.

@marcellobenigno
Last active June 8, 2022 10:41
Show Gist options
  • Save marcellobenigno/7f084ab4d1e58b4b130bf80dec54a906 to your computer and use it in GitHub Desktop.
Save marcellobenigno/7f084ab4d1e58b4b130bf80dec54a906 to your computer and use it in GitHub Desktop.
QGIS Python Snippets
# Layer from Memory
layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' ,'memory')
pr = layer.dataProvider()
pt = QgsFeature()
point1 = QgsPoint(-35.92,-7.24)
pt.setGeometry(QgsGeometry.fromPoint(point1))
pr.addFeatures([pt])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
# Adding a polygon
def run_script(iface):
layer = QgsVectorLayer('Polygon?crs=epsg:4326', 'AI', "memory")
pr = layer.dataProvider()
poly = QgsFeature()
geom = QgsGeometry.fromWkt("POLYGON((-35.94197 -7.25673, -35.94118 -7.21712, -35.88810 -7.21830, -35.88849 -7.25713, -35.94197 -7.25673))")
poly.setGeometry(geom)
pr.addFeatures([poly])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
run_script(iface)
# Loading a vector layer from file sample
data = "/home/marcello/qgis_data/NYC_MUSEUMS_GEO.shp"
layer = QgsVectorLayer(data,"New York City Museums", "ogr")
if not layer.isValid():
print "Layer %s did not load" % layer.name()
QgsMapLayerRegistry.instance().addMapLayers([layer])
# Loading a vector layer from Database (PostgreSQL)
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "sample", "postgres", "postgres")
uri.setDataSource ("public", "municipios", "geom")
layer = QgsVectorLayer(uri.uri(False), "municipios", "postgres")
if not layer.isValid():
print "Layer %s did not load" % layer.name()
QgsMapLayerRegistry.instance().addMapLayers([layer])
# Examining vector layer attributes
data = "/home/marcello/qgis_data/NYC_MUSEUMS_GEO.shp"
layer = QgsVectorLayer(data,"New York City Museums", "ogr")
iter = layer.getFeatures()
for feature in iter:
geom = feature.geometry().asPoint()
x, y = (tuple(geom))
print("x: {}, y: {}".format(x, y))
print(feature.attributes())
print("-=" * 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment