Drupal/OpenLayers: Hide empty layers in the layer switcher

When you you use the Drupal OpenLayers module to display several geometries , e.g. GPX tracks, on a base map one way to do it is to create a separate layer for each geometry to display. If you want the overlay layers to appear in the layer switcher but the actual number of overlay layers varies depending on the node data, all layers, including the empty ones, appear in the layer switcher.

I found a solution to hide empty layers using hook_openlayers_map_alter which works fine in my case. I added the following code to my theme’s template.php:

function <theme>_openlayers_map_alter(&$map) {
   foreach ($map['layer_switcher'] as $k => $n){
      if ($n !== 0){
         if (! $map['layers'][$n]['isBaseLayer'] && array_key_exists('features', $map['layers'][$n])){
            if (!isset($map['layers'][$n]['features'][0]['wkt'])){
               $map['layer_switcher'][$k] = 0;
            }
         }
      }
   }
}