Кластеризация маркеров асинхронных данных на открытых слоях 5 угловая - PullRequest
0 голосов
/ 30 сентября 2019

Я вижу маркеры в своем локальном проекте, когда использую фиктивные данные, но, к сожалению, не вижу их, когда получаю данные из бэкэнда. Исключением является то, что когда я получаю один маркер из бэкэнда, он появляется на карте.

Я отправляю функцию из маркерного компонента в компонент карты:

ngOnInit(): void {
    this.initMarker();
    console.log("#! MARKER INIT");
  }

  ngAfterContentInit() {
    this.setStyle();
  }

  initMarker() {
    const { longitude, latitude } = this.coordinates;
    const coordinates = [longitude, latitude];

    this.marker = new Feature({
      geometry: new Point(fromLonLat(coordinates)),
      coordinates: coordinates,
      data: this.data,
      selected: false,
      name: this.data.type
    });
  }`enter code here`

  setStyle() {
    const markerStyle = this.mMarkerStyleComponent.markerStyle;
    this.marker.setStyle(markerStyle);
    this.mapService.setMarker(this.marker);
  }

В компоненте карты:

 private subscribeMarkerLayerChange(): void {
    this.subscriptions.add(
      this.mapService.markerChanges$.subscribe(resp => {
        this.addMarkerLayers(resp);
      })
    );
  }

  private addMarkerLayers(feature: Feature) {
    const allMapLayersCollection = this.map.getLayers();
    allMapLayersCollection.forEach(existingLayer => {
      if (existingLayer && existingLayer.get('name') === 'MARKERS') {
        const layersMarkersCollection = existingLayer.getLayers();
        layersMarkersCollection.forEach(layerType => {
          if (layerType && layerType.get('vectorType') === 'MARKERS') {
            const cluster = layerType.getSource();
            const vectorSource = cluster.getSource();
            vectorSource.addFeature(feature);
            console.log('# cluster.getFeatures()', cluster.getFeatures());
          }
        });
      }
    });
  }

   private addMarkersLayer() {
    var vectorSource = new VectorSource({ features: [] });

    var clusterSource = new Cluster({
      distance: 40,
      source: vectorSource,
      clusterType: 'MARKERS'
    });

    const styleCache = {};
    const vectorLayer = new VectorLayer({
      vectorType: 'MARKERS',
      source: clusterSource,
      style: function(feature) {
        console.log('# INIT feature');
        const size = feature.get('features').length;
        let style = styleCache[size];
        if (!style) {
          style = new Style({
            image: new Circle({
              radius: 10,
              stroke: new Stroke({
                color: '#fff'
              }),
              fill: new Fill({
                color: '#3399CC'
              })
            }),
            text: new Text({
              text: size.toString(),
              fill: new Fill({
                color: '#fff'
              })
            })
          });
          styleCache[size] = style;
        }
        return style;
      }
    });

    const markersGroup = new LayerGroup({
      layers: [vectorLayer],
      name: 'MARKERS',
      id: constants.MARKERS.id
    });
    const layersCollection = this.map.getLayers();
    layersCollection.insertAt(this.map.get('id'), markersGroup);
  }

Console.log Локальный с макетом:

# cluster.getFeatures() (2) [Feature, Feature]
# cluster.getFeatures() (3) [Feature, Feature, Feature]
# cluster.getFeatures() (4) [Feature, Feature, Feature, Feature]
# cluster.getFeatures() (5) [Feature, Feature, Feature, Feature, Feature]

Из серверной части асинхронно (сборка)

# cluster.getFeatures() (2) [e, e]
# cluster.getFeatures() (2) [e, e]
# cluster.getFeatures() (2) [e, e]
# cluster.getFeatures() (2) [e, e]
# cluster.getFeatures() (3) [e, e, e]
# cluster.getFeatures() (4) [e, e, e, e]
# cluster.getFeatures() (4) [e, e, e, e]
# cluster.getFeatures() (9) [e, e, e, e, e, e, e, e, e]

консольный журнал # Функция INIT

1 Ответ

0 голосов
/ 01 октября 2019

Решение: если хотя бы один маркер из бэкэнда имеет нулевую широту и долготу, ошибки нет, но маркеры не показывают, поэтому мне было трудно найти.

Я добавил оператор if if (longitude && latitude) и все работает.

  initMarker() {
    const { longitude, latitude } = this.coordinates;

    if (longitude && latitude) {
      const coordinates = [longitude, latitude];

      this.marker = new Feature({
        geometry: new Point(fromLonLat(coordinates)),
        coordinates: coordinates,
        data: this.data,
        selected: false,
        name: this.data.type
      });
    }
  }
...