Create dynamic layers with Drupal and Openlayers

Edit: As Pol said in comments, you can use the openlayers_taxonomy module to do this. But it turns out I had to use content types as layers too, so this technique still was useful to me. Thank you Pol :)

I wanted to create layers depending on some taxonomy terms with Openlayers. But the only way to create layers with views is to add one display per layer. What if you want as many layers as terms ? Some Views trickery to the rescue !

  1. Create your Openlayers view.
  2. Add a layer display for the first term.
  3. Create a filter for the term.
  4. Export the view through code.

Then, edit the view code to create one layer per term :
/**
* Implements hook_views_default_views().
*/
function MYMODULE_views_default_views() {
$vocabulary = taxonomy_vocabulary_machine_name_load('VOCABULARY_NAME');
$terms = taxonomy_get_tree($vocabulary->vid);
// Your view code for the master display...
foreach($terms as $term) {
$handler = $view->new_display('openlayers', $term->name, 'layer_' . $term->tid);
// The display code...
$handler->display->display_options['filters']['tid']['value'] = array(
$term->tid => $term->tid,
);
}
// Remaining code...
}

Do the same with your map to generate the layers. Create the map, export it, then edit code :
/**
* Implements hook_openlayers_maps().
*/
function MYMODULE_openlayers_maps() {
$vocabulary = taxonomy_vocabulary_machine_name_load('VOCABULARY_NAME');
$terms = taxonomy_get_tree($vocabulary->vid);
// Your code for the map...
foreach($terms as $term) {
$name = 'MAP_NAME_layer_' . $term->tid;
$openlayers_maps->data['layers'][$name] = $name;
$openlayers_maps->data['layer_activated'][$name] = $name;
$openlayers_maps->data['behaviors']['openlayers_behavior_popup'][$name] = $name;
}
// Remaining code...
}

But hey, we would like the view to be automatically updated on terms addition / edition / removal :
/**
* Implements hook_taxonomy_term_insert().
*/
function MYMODULE_taxonomy_term_insert($term) {
$vocabulary = taxonomy_vocabulary_machine_name_load('VOCABULARY_NAME');
if ($term->vid == $vocabulary->vid) {
views_invalidate_cache();
}
}
 
/**
* Implements hook_taxonomy_term_update().
*/
function MYMODULE_taxonomy_term_update($term) {
MYMODULE_taxonomy_term_insert($term);
}
 
/**
* Implements hook_taxonomy_term_delete().
*/
function MYMODULE_taxonomy_term_delete($term) {
MYMODULE_taxonomy_term_insert($term);
}

That's it !