2

In PyQGIS, I kwnow how to draw polygons starting from a list of points which represent the nodes of the shape. An example of list could be this:

# First polygon
list_1 = [QgsPoint(0,0),QgsPoint(0,50),QgsPoint(50,50),QgsPoint(50,0)]

# Second polygon
list_2 = [QgsPoint(10,10),QgsPoint(10,30),QgsPoint(30,30),QgsPoint(30,20)]

which lead to the representation of these polygons:

enter image description here

If I manually do some operations, I can create a unique polygon like this one:

enter image description here

My question is: Is there a specific rule or a particular way to handle points (in or outside a list) for obtaining the result above? I only know that, for simple polygons, the points must to be ordered clockwise.

My goal is similar to that one in this question, but I think that the context is different here.

  • You need a list of lists where the first and last point match on each sub-list. – xunilk Dec 10 '16 at 0:27
2

You need this kind of list (where the first and last point match on each sub-list):

pol = [[QgsPoint(0,0),QgsPoint(0,50),QgsPoint(50,50),QgsPoint(50,0),QgsPoint(0,0)],
       [QgsPoint(10,10),QgsPoint(10,30),QgsPoint(30,30),QgsPoint(30,20),QgsPoint(10,10)]]

pol_wkt = QgsGeometry.fromPolygon(pol).exportToWkt()

print pol_wkt

I created an objet of QgsGeometry (Python Console of QGIS) to get its expression in WKT format. By using QuickWKT plugin, it can be observed that the result is identical to yours.

enter image description here

Editing Note:

As order (outer ring must include inner rings) and intersection of inner polygons is very important, it could be necessary to validate the geometry before printing it. In next case, where the original order of sub-lists was interchanged, the geometry is not valid:

pol = [[QgsPoint(10,10),QgsPoint(10,30),QgsPoint(30,30),QgsPoint(30,20),QgsPoint(10,10)],
       [QgsPoint(0,0),QgsPoint(0,50),QgsPoint(50,50),QgsPoint(50,0),QgsPoint(0,0)]]

if QgsGeometry.fromPolygon(pol).isGeosValid():
    pol_wkt = QgsGeometry.fromPolygon(pol).exportToWkt()

    print pol_wkt

else:
    print "geometry is not valid"
  • + 1 That's exactly what I was looking for, thanks! =) – mgri Dec 10 '16 at 8:54
  • 1
    Please, see my 'Editing Note'. – xunilk Dec 10 '16 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.