Viglino / ol-ext

Cool extensions for Openlayers (ol) - animated clusters, CSS popup, Font Awesome symbol renderer, charts for statistical map (pie/bar), layer switcher, wikipedia layer, animations, canvas filters.
https://viglino.github.io/ol-ext/
Other
1.25k stars 462 forks source link

Adding trigger functions in Feature Popup overlay #1067

Open liyunooi opened 5 months ago

liyunooi commented 5 months ago

Hi,

I am using your library to display some information via Feature popup overlay. I would like to be able to set a function to trigger a call-to-action upon clicking on the value of an attribute inside the Feature popup overlay.

May I know how would this be handled?

I tried using direct handling by setting the value as a string like so: <a href="http://google.com" target="_blank">${value}</a>

But it seems like the popup overlay does not accept direct html modifications to the value.

Is there any workaround for this?

Thank you.

Viglino commented 4 months ago

You can set a link as value using templates and listen to click event on popup show:

var popup = new ol.Overlay.PopupFeature({
    ...
    template: {
         attributes: {
          'myatt': { 
            title: 'My attribute',  // attribute's title
            format: function(val, f) { 
              return '<a>' + val + '</a>'
            }
          },
        }
    }
});
map.addOverlay (popup);

// Set listener on show
popup.on('show', (e) => {
    popup.element.querySelector('A').addEventListener('click', console.log)
})
Viglino commented 4 months ago

PS I've added a 'attribute' event in the last commit https://github.com/Viglino/ol-ext/commit/9ca2774ea2b05f036770f8f784ad1e76b94c1d04 to make it easier:

popup.on('attribute', function(e) {
  // the attribute
  var value = e.feature.get(e.attribute)
}