Reputation: 3896
I want to add click event to ol.Overlay in OpenLayers. What would be the best way to do this?
Reason for using ol.Overlay: I want to add a custom marker with image and text that could be changed dynamically. For this, I am using ol.Overlay to add HTML in element as follows:
// Add markers
var marker = new ol.Overlay({
position: ol.proj.fromLonLat(lng1, lat1),
positioning: 'center-center',
element: $(getMarkerContent())
});
map.addOverlay(marker);
function getMarkerContent() {
var content = "<div>Name<........>";
return content;
}
I have tried following:
Added onclick
event to on element - this worked
Added marker.on('click', function(evt){});
but it is never called
Is there a better way to do this ?
Upvotes: 1
Views: 6288
Reputation: 6041
Try to set the click handler on the overlay element and not directly on the overlay:
var textElement = $('<p class="overlay text">Text</p>');
var overlay = new ol.Overlay({
position: pos,
element: textElement
});
map.addOverlay(overlay);
textElement.click(function(evt) {
console.log('click');
});
Upvotes: 3