Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Moving vector layer geometry


Sometimes, you need to change the location of a feature. You can do this by deleting and re-adding the feature, but PyQGIS provides a simple way to change the geometry.

Getting ready

You will need the New York City museums' shapefile, which you can download as a ZIP file from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.

Extract this shapefile to /qgis_data/nyc.

How to do it...

We will load the shapefile as a vector layer, validate it, define the feature ID we want to change, create the new geometry, and change the feature in the layer. To do this, perform the following steps:

  1. Start QGIS.

  2. From the Plugins menu, select Python Console.

  3. First, load the layer and validate it:

    vectorLyr =  QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
    vectorLyr.isValid()
    
  4. Next, define the feature ID we are interested in changing:

    feat_id = 22
    
  5. Now, create the new point geometry, which will become the new location:

    geom = QgsGeometry.fromPoint(QgsPoint...