官术网_书友最值得收藏!

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(-74.20378,40.89642))
    
  6. 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.

主站蜘蛛池模板: 乐亭县| 琼海市| 新绛县| 景泰县| 温泉县| 航空| 玛曲县| 疏勒县| 阳原县| 乌拉特后旗| 翁牛特旗| 津南区| 康马县| 茶陵县| 南昌市| 孟连| 甘泉县| 武鸣县| 明光市| 察隅县| 平度市| 乐山市| 青浦区| 聂荣县| 舟山市| 邵东县| 濮阳县| 常宁市| 三穗县| 肥乡县| 星子县| 德庆县| 黔南| 白山市| 毕节市| 体育| 扎赉特旗| 通州市| 商城县| 沅陵县| 西峡县|