# Creating polygon feature from list with points using PyQGIS

I´m trying to build a polygon from a list of coordinates. I have the coordinates in different ways as:

pointsfloat
[(583899.8, 8177297.19), (583900.23, 8177262.52), (583896.49, 8177262.47), (583895.96, 8177297.29), (583899.8, 8177297.19)]


or

coordinates
[583899.8, 8177297.19, 583900.23, 8177262.52, 583896.49, 8177262.47, 583895.96, 8177297.29, 583899.8, 8177297.19]


When I try to convert it to a QgsPoint I always lose the decimals digits, it's converting the numbers to integer automatically.

How can I generate the polygon feature from those vertices?

• Can you post the code that creates the polygon feature so we can evaluate it? Commented Feb 20, 2017 at 0:55

# QGIS v3.x

You can do it in this way:

coords = [(583899.8, 8177297.19), (583900.23, 8177262.52), (583896.49, 8177262.47), (583895.96, 8177297.29), (583899.8, 8177297.19)]
polygon = QgsGeometry.fromPolygonXY( [[ QgsPointXY( pair[0], pair[1] ) for pair in coords ]] )


Now you have a polygon. To see its coordinates:

polygon.asWkt(2)
# Prints:
# 'Polygon ((583899.8 8177297.19, 583900.23 8177262.52, 583896.49 8177262.47, 583895.96 8177297.29, 583899.8 8177297.19))'


As you see, you aren't losing decimals.

If you want to quickly visualize that polygon, you could use the QuickWKT plugin and paste the WKT representation you just got.

# QGIS v2.x

You can do it in this way:

coords = [(583899.8, 8177297.19), (583900.23, 8177262.52), (583896.49, 8177262.47), (583895.96, 8177297.29), (583899.8, 8177297.19)]
polygon = QgsGeometry.fromPolygon( [[ QgsPoint( pair[0], pair[1] ) for pair in coords ]] )


Now you have a polygon. To see its coordinates:

polygon.exportToWkt(2)
# Prints:
# u'Polygon ((583899.8 8177297.19, 583900.23 8177262.52, 583896.49 8177262.47, 583895.96 8177297.29, 583899.8 8177297.19))'


As you see, you aren't losing decimals.

If you want to quickly visualize that polygon, you could use the QuickWKT plugin and paste the WKT representation you just got.

• Thanks German!!! I have been trying things like QgsGeometry.fromPolygon([[QgsPoint(x1,y1),QgsPoint(x2,y2), QgsPoint(x3,y3),QgsPoint(x4,y4), QgsPoint(x1,y1)]]) or converting between types and i cant. Your solution is great. Regards Commented Feb 20, 2017 at 15:16