[GIS] Creating indexed vector grid in QGIS

field-calculatorlabelingqgisvectorvector-grid

at the moment I am trying to create an indexed vector grid via "vector -> research tools -> vector grid…", in the following format:

A1 A2 A3 ...
B1 B2 B3 ...
C1 C2 C3 ...
.. .. ..

The creation of the grid is no Problem, but I am stuck with labeling the individual polygons.

I already wrote an Excel Visual Basic Project, which creates a script for the field calculator and helps me to label each row from A to X. Now I want to label the columns with numbers from the first one to the last. Do you have any idea how I could use the @row_number to specify the column?

Here is the output of the script for the field calculator:

CASE
WHEN ID>-1 AND ID<5 THEN concat('A',@row_number)
ELSE
CASE
WHEN ID>4 AND ID<10 THEN concat('B',@row_number)
ELSE
CASE
WHEN ID>9 AND ID<15 THEN concat('C',@row_number)
ELSE
CASE
WHEN ID>14 AND ID<20 THEN concat('D',@row_number)
ELSE
CASE
WHEN ID>19 AND ID<25 THEN concat('E',@row_number)
END
END
END
END
END

Best Answer

You have two possibilities...


Existing plugin

there's already a plugin to do this called Create Indexed Vector Grid (which I wrote, mainly so I could do road atlas-style maps of cities).

Once installed it appears under Vector > Create Indexed Grid menu. It'll add the labels as fields to each cell for you (and optionally, add "headers" for your rows and columns).

It's experimental, so if you can't see it in plugins manager you'll need to enable the "show experimental plugins". There's a link to a blog post explaining how to use it in the plugin description in Plugin Manager.


With inbuilt create vector grid

That might not be suitable, though - the plugin only works on the canvas extent or layer extent, it doesn't let you set the extent manually.

Use the modulo operator to get the column number, and simple integer division to get the row number. That way you only need one expression, and don't need to write code to generate a script.

I created a grid using Create Vector Grid and assigned a new field with @row_number (called this field idd). As you can see it's 15 cells wide wide, and cells are numbered as follows...

enter image description here

Now, assuming you want 1-indexed (so you assigned a value of 1 to first cell)

  • row number is to_int(floor(to_int(idd-1)/15))
  • column number is (idd-1)%15, which we use to convert to a character

the following single expression should work

char(65+(to_int(floor(to_int(idd-1)/15)))) || substr('0123456789ABCDEF', ((idd-1)%15)+2,1) 

that turned out to be more complex than I thought, largely because the divide is a floating point operation, rather than an integer division (like // in python)

example...

enter image description here

Note that the definition of substr changed in QGIS 2.14 so this will need to be tweaked for older versions of QGIS.

Related Question