I would like to be able to run custom JavaScript code whenever an Openlayers Popup is displayed.

Adding the following lines to the end of the popup.js file accomplishes this goal.

        // Allow other code to be triggered when a popup is displayed.
        jQuery(document).trigger('openlayers.Component:Popup', { 'overlay': overlay, 'evt': evt });
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

m.stenta created an issue. See original summary.

m.stenta’s picture

Status: Active » Needs review
FileSize
577 bytes

Patch attached.

The following code illustrates an example usage. Simply put this into a javascript file and include in the same page as your map with drupal_add_js().

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $(document).on('openlayers.Component:Popup', function (event, options) {

        console.log('popup!');

        // The popup container is passed in via options.container
        // The parent event click is passed in as options.evt

      });
    }
  };
}(jQuery));

Status: Needs review » Needs work

The last submitted patch, 2: openlayers_popup_trigger-2687781-1.patch, failed testing.

jantoine’s picture

Status: Needs work » Needs review

This is a much better approach than what I was trying to do which was to copy how the GeoJSON source component is extended. Instead of using drupal_add_js() to include your javascript on a specific page, hook_openlayers_object_postprocess_alter() might be more robust as it is path independent and will load your javascript no matter where your maps/popups are loaded.

Example code:

<?php
/**
 * Implements hook_openlayers_object_postprocess_alter().
 */
function example_module_openlayers_object_postprocess_alter(array &$build, \Drupal\openlayers\Types\ObjectInterface $context) {
  // If this is our map.
  if (strpos($context->getId(), 'example-module-map') !== FALSE) {
    // If this is for the Popup plugin.
    if ($context->getPluginId() == 'Popup') {
      // Attach our JavaScript.
      $path = drupal_get_path('module', 'example_module') . '/js/popup.js';
      $build['#attached']['js'][] = array(
        'data' => $path,
        'group' => 'openlayers',
        'type' => 'file',
        'weight' => 25,
      );
    }
  }
}
?>
m.stenta’s picture

Thanks for the JS loading tip @jantoine! And for trying the patch! :-)

If it's working for you, feel free to mark this issue "Reviewed & tested by the community".

jantoine’s picture

Status: Needs review » Reviewed & tested by the community

This is working great for us!