'OpenLayers add marker by doubleclick on the map

I'm trying to add a new marker on the map in the coordinates that the user select by doubleclick on the map. I read lot of documentation online but my evt.coordinate is undefined. There is the code

  this.map.getViewport().addEventListener("dblclick", function(evt) {
    this.addMarker(evt.coordinate)
  }.bind(this));

MyClientLibrary.prototype.addMarker= function(coordinates) {
  console.log(coordinates);
  var marker = new OpenLayers.Feature(new OpenLayers.geom.Point(coordinates));
  var zIndex = 1;
  marker.setStyle(new OpenLayers.style.Style({
    image: new OpenLayers.style.Icon(({
      anchor: [0.5, 36], 
      anchorXUnits: "fraction",
      anchorYUnits: "pixels",
      opacity: 1,
      src: "mapIcons/pinother.png", 
      zIndex: zIndex
    })),
    zIndex: zIndex
  }));
  vectorSource.addFeature(marker);
}

How can I do? Thanks.



Solution 1:[1]

Try to listen for a certain type of event via on:

this.map.on('dblclick', event => {
  console.log(event.coordinate);
});

I am not 100% sure, but I guess, using getViewport() might cause a problem, because it returns the viewport of the map.

Edit:

this.map.on('dblclick', function(event) {
  console.log(event.coordinate);
}.bind(this));

Solution 2:[2]

Done in this way:

    var lonLat = ol.proj.fromLonLat([Lon, Lat]);
    var feature=new ol.Feature({
      geometry: new ol.geom.Point(lonLat),
      type:"Point"
    })
    feature.set("info",Info);
    var layer = new ol.layer.Vector({
      source: new ol.source.Vector({
        features: [feature]
      }),
      style: new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: pinPath,
          scale: 1
        })
      })
    });
    layer.set("layerId", "Point");
    if (this.map) {
      this.map.addLayer(layer);
      this.map.getView().animate({ zoom: Zoom, center: lonLat });
  
    }
    else {
      setTimeout(function () {
        this.map.addLayer(layer);
        this.map.getView().animate({ zoom: Zoom, center: lonLat });
      }.bind(this), 500);
    }
  }
  

This part of code is called on the dblclick event

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ricef