角度仅在自上次轮询以来已更改的对象时更新对象

时间:2018-10-05 04:57:36

标签: javascript angular typescript asp.net-web-api leaflet

我从我的Web api轮询数据以使用标记填充地图。标记具有位置,Im通过以下方式保存标记

  allMarkers: Map<Number, Leaflet.Marker> = new Map();

此刻,我每次轮询数据时都会刷新标记,即每10秒刷新一次。我想做的只是刷新位置实际已改变的标记。有什么有效的方法可以做到吗?我尝试使用“ oldAllMarkers”和“ newAllMarkers”,但是并没有做很多事情。

请参阅下面的代码,如果需要添加任何内容以使事情变得清楚,请告诉我。


// ngOnInit with a bunch of things. Here is where I set up my map and poll 
//  my data with the use of my subscribeToData function.
ngOnInit() {
    // Init map
    this.map = new Leaflet.Map('mapid', {}).setView([this.lng, this.lat], 10);
    this.tiles = new Leaflet.TileLayer(
      ,
      {
        attribution: `Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors,
           <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>,
           Imagery © <a href="https://www.mapbox.com/">Mapbox</a>`,
        maxZoom: 18,
        minZoom: 1,
        id: 'mapbox.streets',
        accessToken:

          }
        ).addTo(this.map);

    // init vehicles details
    this.store.select(fromStore.getAllVehicleDetails).subscribe(data => {
      this.vehicleDetails = data;


      this.setMarkers(this.selected);          

      // set the selected vehicle
      this.vehicleDetail = this.getVehicleDetail(this.selected);

      // set/refresh the markers
      this.setMarkers(this.selected);     

    });
    this.store.dispatch(new fromStore.LoadVehicleDetails());
    this.subscribeToData();
  }

 setMarkers(id: number) {
    for (let i = 0; i < this.vehicleDetails.length; i++) {
      // Refresh markers
      if (this.allMarkers.get(this.vehicleDetails[i].id)) {
        const tempMarker = this.allMarkers.get(this.vehicleDetails[i].id);
        this.allMarkers.delete(this.vehicleDetails[i].id);
        if (tempMarker) {
          this.map.removeLayer(tempMarker);
          console.log('refresh map marker');
        }
      }

        // Creating the markers
        this.getIcon(this.vehicleDetails[i], status);

        // set markers to our hashpmap.
        if (this.markers) {
          this.allMarkers.set(this.markers.options.vehicleId, this.markers);
        }
     }
      // hide progress bar
      this.loading = false;
    }
  }

1 个答案:

答案 0 :(得分:0)

我解决了!对于任何有兴趣的人,这就是我的做法:

updateVehicleStates(values: VehicleDetail[]) {
    for (let i = 0; i < values.length; i++) {
      const oldValue = this.vehicleDetails[i];
      // set the marker during initialization
      if (!oldValue) {
        this.setMarker(values[i]);
      } else {
        // only updates the marker if its position has changed
        if (values[i].position) {
          if (
            oldValue.position.longitude !== values[i].position.longitude ||
            oldValue.position.latitude !== values[i].position.latitude
          ) {
            this.setMarker(values[i]);
          }
        }
      }
    }
    // update our vehicles
    this.vehicleDetails = values;
  }