- QGIS Python Programming Cookbook
- Joel Lawhead
- 260字
- 2021-07-23 19:48:57
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:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, load the layer and validate it:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
- Next, define the feature ID we are interested in changing:
feat_id = 22
- Now, create the new point geometry, which will become the new location:
geom = QgsGeometry.fromPoint(QgsPoint(-74.20378,40.89642))
- Finally, change the geometry and replace it with our new geometry, specifying the feature ID:
vectorLyr.dataProvider().changeGeometryValues({feat_id : geom})
How it works...
The changeGeometryValues()
method makes editing a snap of the fingers. If we had to delete and then re-add the feature, we would have to go through the trouble of reading the attributes, preserving them, and then re-adding them with the new feature. You must, of course, know the feature ID of the feature you want to change. How you determine this ID depends on your application. Typically, you will query the attributes to find a specific value, or you can do a spatial operation of some sort.
- Visual C++程序設計學習筆記
- Three.js開發指南:基于WebGL和HTML5在網頁上渲染3D圖形和動畫(原書第3版)
- Oracle 12c中文版數據庫管理、應用與開發實踐教程 (清華電腦學堂)
- Learning Elixir
- C語言最佳實踐
- HTML5游戲開發案例教程
- 云計算通俗講義(第3版)
- The Complete Coding Interview Guide in Java
- 高級語言程序設計(C語言版):基于計算思維能力培養
- Java:High-Performance Apps with Java 9
- 精通Python自動化編程
- Mastering Akka
- Programming with CodeIgniterMVC
- Apache Camel Developer's Cookbook
- 從零開始學Android開發