QGIS Polygon Color Change – How to Change Polygon Color Based on Background Map Visibility

colorpolygonqgisvisibility

I have a map with borders and different "background maps", e.g. OpenStreetMap and Google Satellite. When the Google Satellite Map is in the background, the borders are the best visible in white color. With OpenStreetMap turned visible, it is the color black.

Is there a way to change the color of a polygon (f.e. state border) depending on whether OpenStreetMap is visible or not?

Best Answer

An alternative if you want the symbology to show up correctly in legends and customise more layer settings depending on basemap, is to use style presets and map themes. This will also let you rename the basemap layers without needing to update the expression if using a data defined override (unless you use the layer's uuid).

Set up 'black' and 'white' style presets for your borders layer

  1. Click View > Panels > Layer Styling to open up the Layer Styling panel (easier to access).
  2. Select your borders layer from the layers panel, and in the Layer Styling click the multiple paintbrush icon tab - see left hand side of image below. This will show you the presets for that layer (usually will just say 'default').
  3. With your borders layer showing a white outline, press the plus icon in the layer styling tab (see red circle in image below), and call this new style 'White'
  4. Press the plus icon again and call the new style 'Black'
  5. While the 'Black' style is active in the list, go to Symbology (single paintbrush) and change the outline to black.

enter image description here

Set up map themes

  1. With the 'Black' style active on your borders layer, switch on OSM and switch off Google Satellite visibility in your layers panel. This is where you can also toggle the visibility of or theme other layers as required
  2. Go to map themes (eye icon) in your layers panel, and add new theme. Call this 'OSM'
  3. Now go to your borders layer, change the preset to 'White' in the Layer Styling panel
  4. Switch on Google Satellite and switch off OSM (and toggle styles/visibility of other layers as required).
  5. Now add a new map theme and call this 'Google Satellite'

enter image description here

You can now toggle between map themes and set them up as required in your map layouts as well by getting the map item to follow whatever theme you select, regardless of what is displayed on the canvas.

See below for example. Note how the active layer style changes (in the layer styling panel to the right) when the map theme is changed.

enter image description here

Related Question