Автоматизация компоновки карты с помощью инструмента создания атласа (QGIS3)

Если вы занимаетесь созданием печатных или веб-карт, возможно, перед вами возникает задача создания по некоторому шаблону большого количества карт - как правило, по одной на каждую административную единицу или область интереса. Создание таких карт вручную может отнимать много времени, и, если вы планируете регулярно их обновлять, эта работа может стать утомительной. QGIS содержит инструмент «Атлас», который поможет вам создать шаблон карты и позволит публиковать множество карт разных географических регионов. Если вы не знакомы с основами создания макетов карт, пожалуйста, изучите урок Создание карты.

Обзор задачи

В этом уроке показано, как создать карту водно-болотных угодий для каждого округа в штате Гавайи.

Также вы получите следующие навыки

  • Использовать стиль Инвертированные полигоны для заливки областей за пределами полигонов.

  • Составлять выражения для стилистики, основанной на правилах, для отображения только текущего объекта в Атласе.

  • Составлять выражения для создания динамических подписей в Компоновщике карт.

  • Использовать стиль Разбивка фигуры для создания двухцветной заливки полигонов.

Получение данных

Мы будем использовать ГИС-данные с сайта Управления по планированию штата Гавайи

Загрузите слой Wetlands из категории Biologic and Ecologic.

Загрузите слой Census County Boundaries 2010 из категории Cultural and Demographic.

Также вы можете напрямую скачать оба набора данных по ссылкам ниже:

HI_Wetlands.shp.zip

county10.shp.zip

Источник данных: [HAWAII]

Порядок действий

  1. В браузере QGIS найдите архив HI_Wetlands.shp.zip и откройте его. Перетащите файл HI_Wetlands_Poly.shp в область карты. Данный слой содержит полигоны водно-болотных угодий штата Гавайи.

../../_images/110.png
  1. Поскольку мы хотим создать отдельную карту на каждый округ, нам необходим слой с полигонами этих округов. Откройте архив county10.shp.zip. Выберите файл county10.shp и перетащите его в область карты.

../../_images/210.png
  1. Временно отключите видимость слоя HI_Wetlands_Poly, чтобы увидеть полигоны слоя county10. Слой содержит 5 объектов, каждый из которых связан с одним или несколькими полигонами и отражает один из пяти округов. Мы используем этот слой в качестве слоя покрытия, чтобы автоматически создать 5 отдельных карт - по одной для каждого объекта.

../../_images/35.png
  1. Включите видимость слоя HI_Wetlands_Poly. Откройте Проект ‣ Создать макет….

../../_images/41.png
  1. Оставьте пустым название макета и нажмите OK.

../../_images/51.png
  1. В окне Создание макета выберите Добавить объект ‣ Добавить карту.

../../_images/61.png
  1. Drag a rectangle while holding the left mouse button where you would like to insert the map.

../../_images/71.png
  1. In QGIS3, the Atlas tab is not visible by default. Select View ‣ Panels ‣ Atlas.

../../_images/81.png
  1. Switch to the Atlas tab. Check the Generate an atlas box.

../../_images/91.png
  1. Select the county10 as the Coverage layer. This will indicate that we want to create 1 map each for every polygon feature in the county10 layer. You can also check the Hidden coverage layer so that the features themselves will not appear on the map.

../../_images/104.png
  1. Switch to the Item Properties tab. Scroll down and check the Controlled by atlas box. This will indicate the layout that the content of the map displayed in this item will be determined by the Atlas tool.

Примечание

You must enable the Generare an atlas box in the Atlas tab, otherwise the Controlled by atlas checkbox will be diasbled.

../../_images/114.png
  1. Now that you have configuring the Atlas settings, go to Atlas ‣ Preview Atlas.

../../_images/124.png
  1. You will see the map refresh and show how individual map will look like. You can preview how the map will look for each of the county polygons. Go to Atlas ‣ Next Feature. Atlas will render the map to the extent of the next feature in the coverage layer.

../../_images/133.png
  1. Let’s add a label to the map. Go to Layout ‣ Add Label.

../../_images/143.png
  1. Under the Item properties tab, locate the Main properties section and click Insert an Expression… button.

../../_images/153.png
  1. The label of the map can use the attributes from the coverage layer. The concat function is used to join multiple text items into a single text item. In this case we will join the value of the NAME10 attribute of the county10 layer with the text County of. Add an expression like below and click OK.

concat('County of ', "NAME10")
../../_images/163.png
  1. Delete the leading Lorem ipsum placeholder text so that the textbox contains only the expression. Scroll down to the Appearance section and click on the Font dropdown. Choose the font and adjust the size to your liking.

../../_images/173.png
  1. Choose Center as the Horizontal alignment and Middle as the Vertical alignment option.

../../_images/182.png
  1. Add another label and enter Wetlands Map under the Main properties. Since there is no expression here, this text will remain the same on all maps.

../../_images/192.png
  1. Go to Atlas ‣ Last Feature and verify that the map labels do work as intended. You will notice that the wetland map has polygons extending out in the ocean that looks ugly. We can change the style to that areas outside the county boundaries are hidden.

../../_images/202.png
  1. Switch to the main QGIS window. Right-click the county10 layer and select Properties.

../../_images/212.png
  1. In the Symbology tab, select the Inverted polygons renderer. This renderer styles the outside of the polygon - not inside. Select white as the fill color and click OK.

../../_images/222.png
  1. You will notice that the polygons extending outside of the county boundaries are now disappeared. In reality, they are hidden by the white color fill extending out from the county polygons because of the Inverted polygons style.

../../_images/232.png
  1. Switch to the Layout window. If we want the effect of the inverted polygons to show, we need to uncheck the Hidden coverage layer box under Atlas tab. Once unchecked, the rendered image will appear clean and areas outside the coverage polygon is not visible.

../../_images/242.png
  1. There is one more problem though. You will notice that in some cases, parts of the map that are outside the coverage layer boundary are still visible. This is because Atlas doesn’t automatically hide other features. This can be useful in some cases, but for our purpose, we only want to show wetlands of the county whose map is being generated. To fix this, switch back to the main QGIS window and right-click the county10 layer and select Properties.

../../_images/252.png
  1. In the Symbology tab, select Rule-based as the Sub renderer. Double-click the area under Rule.

../../_images/261.png
  1. In the Edit rule dialog, click the Expression button next to Filter.

../../_images/272.png
  1. In the Expression string builder, expand the Variables group of functions. The @atlas_featureid variable stores the id of the the currently selected feature. We will construct an expression that will select only the currently selected Atlas feature. Enter the expression as below and click OK.

$id = @atlas_featureid
../../_images/282.png
  1. Close all intermediate dialogs and switch back to the Layout window. Select Map 1 item and click the Update preview button under Item properties tab to see the changes. Notice that now only the area covering the county boundary is shown.

Примечание

If you do not see the Update preview button, it may help to select another Item element first and then select Map 1 again.

../../_images/292.png
  1. We will now add another dynamic label to show the current date. Go to Layout ‣ Add Label and select the area on the map. Click Insert an expression button.

../../_images/302.png
  1. Expand the Date and Time functions group and you will find the $now function. This holds the current system time. The function todate() will convert this to a date string. Enter the expression as below and click OK.

concat('Created on: ', todate($now))
../../_images/312.png
  1. Add another label citing the data source. You may also add other map elements such as a north arrow, scalebar etc. as described in Создание карты tutorial.

../../_images/321.png
  1. We will make one last styling improvement. Switch back to the main QGIS window and right-click the HI_Wetlands_Poly layer and select Properties.

../../_images/331.png
  1. In the Symbology tab, click on Simple fill and select Shapeburst fill as the Symbol layer type. Choose the Two color option and select shades of green and blue that you like. Click OK.

../../_images/341.png
  1. Select Map 1 item and click the Update preview button under Item properties tab to see the changes.

../../_images/351.png
  1. Once you are satisfied with the map layout and styling, go to Atlas ‣ Export Atlas as Images.

../../_images/36.png
  1. Select a directory on your computer and click Choose.

../../_images/37.png
  1. Leave the default options in the Image Export Options and click Save.

../../_images/38.png
  1. The Atlas tool will now iterate through each feature in the coverage layer and create a separate map image based on the template we created. You can see the images in the directory once the process completes.

../../_images/39.png
  1. Here are the map images for refeence.

../../_images/output_1.png ../../_images/output_2.png ../../_images/output_3.png ../../_images/output_4.png ../../_images/output_5.png

If you want to report any issues with this tutorial, please comment below. (requires GitHub account)