OpenLayers - add click event on ol.Overlay

2019-06-13 18:34发布

问题:

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:

  1. Added onclick event to on element - this worked

  2. Added marker.on('click', function(evt){}); but it is never called

Is there a better way to do this ?

回答1:

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');
});

http://jsfiddle.net/jvdv489j/