【问题标题】:geoJSON onEachFeature Mouse EventgeoJSON onEachFeature 鼠标事件
【发布时间】:2018-07-28 22:16:17
【问题描述】:

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

未捕获的类型错误:无法读取未定义的属性“detectChanges”

我可以认为这是因为在构造函数运行之前分配了图层,但在 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);
}

【问题讨论】:

标签: leaflet angular5 ngx-leaflet


【解决方案1】:

您需要确保在您的回调中可以访问正确的this。您可以在 Javascript 中使用 function.bind() 来执行此操作。见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

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

}

let that = this 的技巧是确保您在 click 事件处理程序上没有同样的问题。但是,您也可以使该处理程序成为您类中的一个函数,并使用 bind 来设置 this。

【讨论】:

  • 感谢您快速解决问题的答案:)
  • @reblace 如何嵌套 ngx-leaflet 点击事件?我已经使用上面的示例成功单击多边形以显示位于该多边形内的相关点。然后我希望能够单击各个点以显示更深层次的点。如何使用this 区分这两层?
  • @lauren 单击与多边形重叠的单个点可能会涉及 CSS(例如,指针事件)和可能故意的图层排序。至于区分,您可以将它们分解为单独的 geoJSON 层,并为每个层设置不同的 onEachFeature 属性。
  • @reblace 您使用“.bind(this)”解决方案为您节省了很多时间。我遇到的下一个问题是 layer.on('click',当我在地图中单击它时,事件没有触发。你知道这可能是什么问题吗? layer.on('click', (e) => {e.target.setStyle({fillColor :'red'})}); 我正在使用 Angular 11
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
相关资源
最近更新 更多