geoJSON onEachFeature鼠标事件

时间:2018-02-18 15:25:07

标签: leaflet angular5 ngx-leaflet

我有一个问题,我尝试将onEachFeature Methode用于geoJSON层。我尝试为每个功能分配一个点击监听器。 问题是当我点击某个功能时总是会出现错误:

  

未捕获的TypeError:无法读取未定义的属性'detectChanges'

我可以想到这是因为在构造函数运行之前分配了Layer,但是在ngOnInit函数中执行它也不会工作。如果这是一个很好的方法,那将会很酷:)

  constructor(private changeDetector: ChangeDetectorRef){}

  fitBounds: LatLngBounds;
  geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});

  onEachFeature(feature , layer) {
    layer.on('click', <LeafletMouseEvent> (e) => {
        this.fitBounds = [
            [0.712, -74.227],
            [0.774, -74.125]
        ];
        this.changeDetector.detectChanges();
    });
  }

  layer: Layer[] = [];
  fitBounds: LatLngBounds;
  
  onEachFeature(feature , layer : geoJSON) {
    layer.on('click', <LeafletMouseEvent> (e) => {
        console.log("tets"+e.target.getBounds().toBBoxString());
        this.fitBounds = [
            [0.712, -74.227],
            [0.774, -74.125]
        ];
        this.changeDetector.detectChanges();
    });
  }
  
constructor(private changeDetector: ChangeDetectorRef){}

ngOnInit() {
      let geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
      this.layer.push(geoLayer);
}

1 个答案:

答案 0 :(得分:4)

您需要确保在回调中可以访问正确的function.bind()。您可以使用Javascript中的constructor(private changeDetector: ChangeDetectorRef){} fitBounds: LatLngBounds; geoLayer = geoJSON(statesData, { // Need to bind the proper this context onEachFeature : this.onEachFeature.bind(this) }); onEachFeature(feature , layer) { // 'this' will now refer to your component's context let that = this; layer.on('click', <LeafletMouseEvent> (e) => { that.fitBounds = [ [0.712, -74.227], [0.774, -74.125] ]; // Aliased 'that' to refer to 'this' so it is in scope that.changeDetector.detectChanges(); }); } 执行此操作。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

let that = this

click诀窍是确保您在this事件处理程序上没有遇到同样的问题。但是,您也可以将该处理程序作为类中的函数,并使用bind来设置{{1}}。