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

Creating a vector layer in memory

Sometimes, you need to create a temporary data set for quick output or as an intermediate step in a more complex operation without the overhead of actually writing a file to disk. PyQGIS employs memory layers that allow you to create a complete vector data set, including the geometry, fields, and attributes, virtually. Once the memory layer is created, you can work with it in the same way you would work with a vector layer loaded from disk.

Getting ready

This recipe entirely runs inside the PyQGIS console, so no preparation or external resources are required.

How to do it...

We will create a Point vector layer, named Layer 1 with a few fields and then validate it:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. In the Python console, create a QgsVectorLayer, including fields, and specify it as a memory data provider:
    vectorLyr = QgsVectorLayer('Point?crs=epsg:4326&field=city:string(25)&field=population:nt', 'Layer 1' , "memory")
    
  4. Now, validate the layer and ensure that the console returns True:
    vectorLyr.isValid()
    

How it works...

The QgsVectorLayer requires three arguments. The last argument specifies the type, which in this case is memory. The second argument specifies the layer name. Normally, the first argument is the path to the file on disk, which is used to create the layer. In the case of the memory layer, the first argument becomes the construction string for the layer. The format uses query parameters that follow the convention key = value. We first specify the coordinate reference system and then specify the fields we want. In this case, we specify the first field, a string for city names, and then an integer field for population.

There's more…

You can easily see how describing a layer's attribute table structure in a string can become unwieldy. You can also use a Python-ordered dictionary to build the string dynamically, as shown in the following steps.

  1. First, you need to import the OrderedDict container, which remembers the order in which keys are inserted:
    from collections import OrderedDict
    
  2. Then, build an ordered dictionary that contains attribute names and types:
    fields = OrderedDict([('city','str(25)'),('population','int')])
    
  3. Next, build a string by joining the output of a Python list comprehension that loops through the ordered dictionary:
    path = '&'.join(['field={}:{}'.format(k,v) for k,v in fields.items()])
    
  4. Finally, use this string to define the layer:
    vectorLyr = QgsVectorLayer('Point?crs=epsg:4326&' + path, 'Layer 1' , "memory")
    
主站蜘蛛池模板: 丰镇市| 马公市| 年辖:市辖区| 永定县| 安阳市| 凌源市| 定州市| 阳新县| 依安县| 九寨沟县| 南阳市| 玛多县| 治县。| 合水县| 界首市| 新龙县| 青冈县| 六安市| 九龙城区| 赣榆县| 沽源县| 名山县| 正镶白旗| 永安市| 济源市| 衡阳县| 阿城市| 富裕县| 德州市| 芦溪县| 庐江县| 大港区| 葫芦岛市| 济南市| 孝义市| 六盘水市| 云南省| 诏安县| 扎兰屯市| 酒泉市| 金沙县|