Click feature on marker of open layers version 5

核能气质少年 提交于 2019-12-11 07:46:43

问题


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()
    })



  }

回答1:


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) {


来源:https://stackoverflow.com/questions/56348153/click-feature-on-marker-of-open-layers-version-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!