[GIS] Extract coordinates from vector layer in PyQGIS

coordinatespyqgispythonqgis

In QGIS, I have made a polygon, and from that polygon I have made a vector grid via research tools-> vector grid. The grid covers the entire polygon.

Now I want to extract these grid points in the python console so I can work with them. But I can not figure out how to extract these coordinates.

I have done the following:

Layer = qgis.utils.iface.activeLayer()
provider = Layer.dataProvider()
feat = QgsFeature()
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
geom = feat.geometry()

but from here I do not know what to do. Any help?

Best Answer

The PyQGIS Cookbook is a great resource for such questions, especially this section: http://www.qgis.org/pyqgis-cookbook/vector.html#iterating-over-vector-layer

# retreive every feature with its geometry and attributes
while provider.nextFeature(feat):

  # fetch geometry
  geom = feat.geometry()
  print "Feature ID %d: " % feat.id() ,

  # show some information about the feature
  if geom.vectorType() == QGis.Point:
    x = geom.asPoint()
    print "Point: " + str(x)
  elif geom.vectorType() == QGis.Line:
    x = geom.asPolyline()
    print "Line: " + str(x)
  elif geom.vectorType() == QGis.Polygon:
    x = geom.asPolygon()
    print "Polygon: " + str(x)
  else:
    print "Unknown"
Related Question