Search code examples
javascriptopenlayers-5

Click feature on marker of open layers version 5


I am using open layers library version 5. I need an onClick event on marker to do some business logic. Anybody could help me with this out thankyou. I have tried every code and snippets. I am using this library to react js.

import Feature from "ol/Feature";
  import point from "ol/geom/Point"
  import Style from "ol/style/Style";
  import Icon from "ol/style/Icon";

renderMap = (lat = 24.8856802, lng = 67.0830459) => {
    console.log(lat, lng);
    this.map = new Map({
      target: 'map',
      layers: [
        new TileLayer({
          source: new OSM()
        })
      ],
      view: new View({
        center: fromLonLat([lng, lat]),
        zoom: 17,

      })
    });


    this.makeMarker(24.8856802, 67.0830459, 0);


  }
//here is my marker function 
makeMarker = (lat, lng, index) => {
    let marker = new Feature({
      geometry: new point(fromLonLat([lng, lat])),

    });
    marker.setStyle(new Style({
      image: new Icon(({
        // crossOrigin: 'anonymous',
        src: require("../../assets/images/location-pin.png"),
    enter code here`enter code here`


      }))
    }));
    let vectorSource = new Vector({ features: [marker] })
    var markerVectorLayer = new LVector({
      source: vectorSource,


    });
    this.map.addLayer(markerVectorLayer);
    marker.on("click", () => {
      alert()
    })



  }

Solution

  • Features don't have click events. Similar to this example https://openlayers.org/en/latest/examples/icon.html you will need to listen for click on the map, check if there is a feature at the click pixel and also that feature is your marker

      map.on('click', function(evt) {
        var feature = map.forEachFeatureAtPixel(evt.pixel,
          function(feature) {
            return feature;
          });
        if (feature === marker) {