'addLayer' 个未定义的开放层 angular 4

'addLayer' of undefined openlayers angular 4

我想在openlayers中点击地图添加标记angular 6,我想在我的函数中使用addLayer但是它不起作用?

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

});

尝试使用箭头函数来保持 this 的上下文。

您的代码示例应如下所示:

this.map.on('click', (e) => {
  console.log('Keep the context of this.map: ', this.map);

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

});

以及 this 绑定和 addlayer() 参数,要素几何需要在视图坐标中。 e.coordinate已经在视图坐标中,可以直接使用

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