Search code examples
gisdata-scienceqgis

How to use WKT to draw polygon in qgis?


I have a CSV file with a data field which contains data like bellow

POLYGON ((79.87749999947846 6.997500000409782, 79.88249999947845 6.997500000409782, 79.88249999947845 7.002500000409782, 79.87749999947846 7.002500000409782, 79.87749999947846 6.997500000409782))

I want to draw a polygon by using this data field in qgis. How can i do this?


Solution

  • For example,I have a csv with two columns "Id" and "geom" that geom have your POLYGON example,

    enter image description here

    Go to layer->Add Layer->Add delimited text Layer and browse your csv and the geometry field combobox select the column that have your wkt data,in my case is "geom" and Geometry definition select (WKT) option

    enter image description here

    The result is:

    enter image description here

    In another way, using Python:

    uri ='file:///C://Users//fjraga//Desktop//test.csv?delimiter=%s&crs=epsg:4326&wktField=%s' % (",", "geom")
    lyr = QgsVectorLayer(uri, 'Test','delimitedtext')
    QgsMapLayerRegistry.instance().addMapLayer(lyr)
    

    But if you only want load this WKT geometry using QGIS python console,try with this:

    wkt = "POLYGON ((79.87749999947846 6.997500000409782, 79.88249999947845 6.997500000409782, 79.88249999947845 7.002500000409782, 79.87749999947846 7.002500000409782, 79.87749999947846 6.997500000409782))"
    
    temp = QgsVectorLayer("Polygon?crs=epsg:4326", "result", "memory")
    QgsMapLayerRegistry.instance().addMapLayer(temp)
    
    temp.startEditing()
    geom = QgsGeometry()
    geom = QgsGeometry.fromWkt(wkt)
    feat = QgsFeature()
    feat.setGeometry(geom)
    temp.dataProvider().addFeatures([feat])
    temp.commitChanges()