Search code examples
angular6openlayers

'addLayer' of undefined openlayers angular 4


i want add marker by clicking on the map in openlayers angular 6, i want to use addLayer in my function but it doesn't work?

 this.map.on('click', function (e) {
  console.log(e.coordinate);
  var lonlat = e.coordinate;
  console.log(lonlat);

  var lon = lonlat[0];
  var lat = lonlat[1];
  this.startMarker = new Feature({

    geometry: new Point(fromLonLat([lon, lat])),

  });


  this.vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: [this.startMarker]
    }),

  });

  this.map.addLayer(this.startMarker);

});

Solution

  • As well as the this binding and addlayer() parameter, the feature geometry needs to be in view coordinates. e.coordinate is already in view coordinates, so you can use it directly

    this.map.on('click', function (e) {
    
      this.startMarker = new Feature({
        geometry: new Point(e.coordinate),
      });
    
      this.vectorLayer = new VectorLayer({
    
        source: new VectorSource({
          features: [this.startMarker]
        }),
    
      });
    
      this.map.addLayer(this.vectorLayer);
    
    }.bind(this));