1

I am trying to include the feature count when using the qgis2web PLugin. I have a point layer and I simply want to show the number of features for each specific field.

enter image description here

This is what I see in the layer window of QGIS 3.28.11

I would just like to show the same items with feature counts on the web map.

Taras
  • 32,823
  • 4
  • 66
  • 137

1 Answers1

1

qgis2web does not have an option that adds feature count. You have to do this in qgis before exporting by hand.

I asked for help in this forum and you can see the discussion here. I'll summarize the content of the discussion by adding a way to reset the visibility of the feature count in the name.

To view the feature count in the name of a single layer you will need to activate the python console and run this script, indicating the name of your layer

    # imports
    from qgis.core import QgsProject
# getting a layer by its name
layer = QgsProject.instance().mapLayersByName("YOUR_LAYER_NAME")[0]

# counting features in the layer
n = layer.featureCount()

# setting up a new name
layer.setName(f"{layer.name()} [{n}]")

You will see that the layer name will capture the feature count. If the number of features changes you will have to run the command again.

enter image description here

If you want to write the feature count in the name of each vector layer you will have to run this script

    # imports
    from qgis.core import QgsProject, QgsVectorLayer
# getting all vector layers' ids in the project 
ids = [layer.id() for layer in QgsProject().instance().mapLayers().values() if isinstance(layer, QgsVectorLayer)]

# looping over each layer's id
for id in ids:
    # accessing a layer by its id
    layer = QgsProject.instance().mapLayer(id)

    # getting layer's name
    name = layer.sourceName()

    # counting features in the layer
    n = layer.featureCount()

    # setting up a new name
    layer.setName(f"{name} [{n}]")

If you want to update the feature count you will first need to remove the count with the following script and then run one of the two scripts written above

# imports
from qgis.core import QgsProject, QgsVectorLayer

getting all vector layers' ids in the project

ids = [layer.id() for layer in QgsProject().instance().mapLayers().values() if isinstance(layer, QgsVectorLayer)]

looping over each layer's id

for id in ids: # accessing a layer by its id layer = QgsProject.instance().mapLayer(id)

# getting layer's name
name = layer.sourceName()

# checking if the layer name has the pattern " [numero]"
if " [" in name and name.endswith("]"):
    # removing the " [numero]" part
    new_name = name[:name.rfind(" [")]
    layer.setName(new_name)