I do have a script that collects coordinates from map canvas clicks and stores them in a list called coordinates.
Now I want to create a feature, set its geometry and attributes and add the feature to the data provider. However, I do get the error saying "QgsGeometry.fromPolygon(unknown-type): argument 1 has unexpected type 'list'"
Here's my code:
from PyQt4.QtCore import *
from PyQt4.QtGui import QColor, QInputDialog, QLineEdit
from qgis.core import QGis, QgsMapLayerRegistry
from qgis.gui import QgsMapToolEmitPoint, QgsRubberBand, QgsMapTool
# Create new virtual layer
vlyr = QgsVectorLayer("Polygon", "temporary_polygons", "memory")
dprov = vlyr.dataProvider()
# Add field to virtual layer
dprov.addAttributes([QgsField("name", QVariant.String),
QgsField("size", QVariant.Double)])
vlyr.updateFields()
# Access MapTool
previousMapTool = iface.mapCanvas().mapTool()
myMapTool = QgsMapToolEmitPoint( iface.mapCanvas() )
# create empty list to store coordinates
coordinates = []
# Access ID
fields = dprov.fields()
def drawBand( currentPos, clickedButton ):
iface.mapCanvas().xyCoordinates.connect( drawBand )
if myRubberBand and myRubberBand.numberOfVertices():
myRubberBand.removeLastPoint()
myRubberBand.addPoint( currentPos )
def mouseClick( currentPos, clickedButton ):
if clickedButton == Qt.LeftButton and len(coordinates) == 0:
# create the polygon rubber band associated to the current canvas
global myRubberBand
myRubberBand = QgsRubberBand( iface.mapCanvas(), QGis.Polygon )
# set rubber band style
color = QColor(78, 97, 114)
color.setAlpha(190)
myRubberBand.setColor(color)
#Draw rubberband
myRubberBand.addPoint( QgsPoint(currentPos) )
coordinates.extend(currentPos)
print coordinates
if clickedButton == Qt.LeftButton and len(coordinates) > 0:
myRubberBand.addPoint( QgsPoint(currentPos) )
coordinates.extend(currentPos)
print coordinates
if clickedButton == Qt.RightButton:
# open input dialog
(description, False) = QInputDialog.getText(iface. mainWindow(), "Description", "Description for Polygon at x and y", QLineEdit.Normal, 'My Polygon')
#create feature and set geometry
poly = QgsFeature()
geomP = QgsGeometry.fromPolygon([coordinates])
poly.setGeometry(geomP)
#set attributes
indexN = dprov.fieldNameIndex('name')
indexA = dprov.fieldNameIndex('size')
poly.setAttributes([QgsDistanceArea().measurePolygon(coordinates), indexA])
poly.setAttributes([description, indexN])
# add feature
dprov.addFeatures([poly])
vlyr.updateExtents()
#add layer
iface.mapCanvas().refresh()
QgsMapLayerRegistry.instance().addMapLayers([vlyr])
#delete list
del coordinates[:]
myMapTool.canvasClicked.connect( mouseClick )
iface.mapCanvas().setMapTool( myMapTool )
My understanding from reading similar question is that QgsGeometry.fromPolygon() requires a QgsPolygon object and that I probably have to use geometry.asPolygon() in order to get one. However, I fail to do so. Could s.o. enlighten me please?