1

我正在使用 ngx-leaflet,在向地图添加标记时,由于大量的函数调用(zone.js),应用程序变慢了。我尝试使用 changeDetection 和 ngZone 但无济于事。请帮忙 :)

 constructor(zone: NgZone) {}

onMapReady(map: L.Map) {
    this.map = map;
    this.zone.run(() => {
      this.getPoints();
    });
    L.control.scale({position: 'bottomleft'}).addTo(this.map);
    L.control.zoom({position: 'bottomleft'}).addTo(this.map);
    this.createLegend();
  }

 private updateLayers(pointList: Point[]) {
    this.layers = [];
    let group = L.featureGroup();
    for (let point of pointList) {
      if (point.gps) {
        this.zone.run( ()=> {
          let marker: Marker = L.marker([point.gps.latitude, point.gps.longitude], {icon: this.setIcon(point.status)});
          group.addLayer(marker);
          this.setPopupContent(marker, point);
          this.layers.push(marker);
          this.layers = this.layers.slice();
          this.changeDetector.detectChanges();
        });
      }
    }
    if (pointList.length != 0) {
      this.zone.run(()=> {
        this.leafletDirective.getMap().fitBounds(group.getBounds(), {
          padding: [10, 10],
          animate: false,
          duration: 0.01,
          noMoveStart: true});
      });
    }
  }

在此处输入图像描述

4

1 回答 1

2

如果传单指令输出绑定正在调用该函数,则不需要在 onMapReady 函数中使用 zone.run() 。该调用将已经在 Angular 区域中。

然后,看起来您正在向特征组添加一堆标记以获得边界框。但是,您还将所有标记添加到图层数组中。您可以将 featureGroup 添加到 layers 数组并稍微简化您的代码。

此外,您可以构建新的图层数组,然后在 Angular 区域中对图层数组进行实际更改。这样,每次更新只调用一次(而不是每个标记一次)。

constructor(zone: NgZone) {}

onMapReady(map: L.Map) {
  this.map = map;
  this.getPoints();

  L.control.scale({position: 'bottomleft'}).addTo(this.map);
  L.control.zoom({position: 'bottomleft'}).addTo(this.map);
  this.createLegend();
}

private updateLayers(pointList: Point[]) {
  let group = L.featureGroup();

  pointList.forEach((point: Point) => {
    if (point.gps) {
        let marker = L.marker(
          [point.gps.latitude, point.gps.longitude],
          {icon: this.setIcon(point.status)});
        group.addLayer(marker);
        this.setPopupContent(marker, point);
      }
  });

  if (pointList.length != 0) {
    this.leafletDirective.getMap().fitBounds( group.getBounds(), {
      padding: [10, 10],
      animate: false,
      duration: 0.01,
      noMoveStart: true
    });
  }

  // The change to the input bound layers array is the only thing
  // that needs to be run in the angular zone
  this.zone.run(() => {
    this.layers = [ group ];
  });

}
于 2018-06-05T03:14:44.133 回答