角度为4的未定义openlayers的'addLayer'

时间:2018-12-25 11:08:21

标签: angular6 openlayers

我想通过单击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);

});

2 个答案:

答案 0 :(得分:0)

尝试使用箭头功能保持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);

});

答案 1 :(得分:0)

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