Angular & OpenLayers - Проблемы со свойством forEachFeatureAtPixel и onclick - PullRequest
0 голосов
/ 23 мая 2018

Я программирую карту с помощью OpenLayers (4.6.5) в Angular (6).У меня есть кнопка, содержащая меню карты, содержащее два флажка.Я хочу показать или скрыть некоторые конкретные маркеры, установив флажки.Каждый флажок заставляет появиться определенный тип маркеров.Когда я нажимаю на маркер, я хочу сделать всплывающее окно с информацией (в файлах GeoJSON, по одному для каждого типа маркеров).

У меня есть полностью функциональный код в простом файле HTML, и теперь я хочусделать то же самое с Angular, флажки являются функциональными, но когда я нажимаю на маркер, у меня появляется ошибка forEachFeatureAtPixel (если я щелкаю в любом месте на карте, у меня появляется ошибка onclick (из функции close.onclick))

app.component.ts:

import { Component, OnInit } from '@angular/core';

import OlMap from 'ol/map';
import OlWMS from 'ol/source/tilewms';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/view';
import VectorLayer from 'ol/layer/vector';
import VectorSource from 'ol/source/vector';
import Point from 'ol/geom/point';
import Style from 'ol/style/style';
import IconStyle from 'ol/style/icon';
import WFS from 'ol/format/wfs';
import GeoJSON from 'ol/format/geojson';
import Overlay from 'ol/overlay';
import feature from 'ol/feature';
import OlSwitch from 'ol-layerswitcher';
import Group from 'ol/layer/group';
import $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  map: OlMap;
  gny_bright: OlWMS;
  gny_bright_mobile: OlWMS;
  wms_gnybrightl93: OlWMS;
  wms_gnybrightl93mobile: OlWMS;
  wms_gnybrightgrey: OlWMS;
  wms_gnybrightgreyl93: OlWMS;
  wms_gnyorthol93: OlWMS;
  wms_gnyorthol93_mobile: OlWMS;
  wms_pistes_c: OlWMS;
  layer: OlTileLayer;
  view: OlView;
  layerSwitcher: OlSwitch;
  WFS: WFS;
  vectorLayer_parking: VectorLayer;
  vectorLayer_piscine: VectorLayer;
  parkingLayer: VectorSource;
  piscineLayer: VectorSource;
  piscine: Style;
  markers: feature;
  popup: Overlay;

  constructor() {
  }

  handleSelected1($event) {
    if($event.target.checked === true) {
      this.map.addControl(this.vectorLayer_piscine);
      this.vectorLayer_piscine.setStyle(this.piscine);
      this.map.addOverlay(this.popup);
    } else {
      this.map.removeControl(this.vectorLayer_piscine);
      this.map.removeOverlay(this.popup);
    }
  }

  handleSelected2($event) {
    if($event.target.checked === true) {
      this.map.addControl(this.vectorLayer_parking);
      this.vectorLayer_parking.setStyle(this.markers);
      this.map.addOverlay(this.popup);
    } else {
      this.map.removeControl(this.vectorLayer_parking);
      this.map.removeOverlay(this.popup);
    }
  }

  ngOnInit() {

    {...}

    //popup

    var element = document.getElementById('popup');

    this.popup = new Overlay({
      element: element,
      autoPan: true,
      offset: [0, -30]
    });

    //Fonction d'affichage des popups

    var content_element = document.getElementById('popup-content');

    this.map.on('click', function(evt){
    var closer = document.getElementById('popup-closer');

    closer.onclick = () => {
      this.popup.setPosition(undefined);
      closer.blur();
      return false;
    };

    console.log(this.popup);

    var feature = this.map.forEachFeatureAtPixel(evt.pixel,
      function(feature) {
        return feature;
      });
    if (feature) {
      var geometry = feature.getGeometry();
      var coord = geometry.getCoordinates();

      if(feature.get('name') != null) {
        var content = '<center><h2>' + feature.get('name') + '</h2></center>' + '<br>';
      } else {
        var content = '<center><h2>' + feature.get('NOM') + '</h2></center>' + '<br>';
      }

      if(feature.get('addr:street') != null) {
        content += '<h5>' + '<i>Adresse : </i>' + feature.get('addr:street') + '</h5>';
      } else if(feature.get('ADRESSE') != null) {
        content += '<h5>' + '<i>Adresse : </i>' + feature.get('ADRESSE') + '</h5>';
      } else {
        null;
      }

      if(feature.get('phone') != null) {
        content += '<h5>' + '<i>Numéro de téléphone : </i>' + feature.get('phone') + '</h5>';
      }

      if(feature.get('website') != null) {
        content += '<h5>' + '<i>Site internet : </i>' + '</h5>' + '<p>' + feature.get('website') + '</p>';
      }

      if(feature.get('CAPACITE')!=null) {
        content += '<h5>' + '<i>Capacité : </i>' + feature.get('CAPACITE') + '</h5>';
      }

      if(feature.get('PLACES')!=null) {
        content += '<h5>' + '<i>Places disponibles : </i>' + feature.get('PLACES') + '<h5>';
      }

      content_element = document.getElementById('popup-content');
      content_element.innerHTML = content;
      this.popup.setPosition(coord);
    }
  });

    this.map.on('pointermove', (e) => {
    if (e.dragging) {
      return;
    };
    var pixel = this.map.getEventPixel(e.originalEvent);
    var hit = this.map.hasFeatureAtPixel(pixel);

    this.map.getViewport().style.cursor = hit ? 'pointer' : '';
    });
  }
}

Я поместил console.log в 'this.popup', чтобы узнать, в чем проблема, потому что я получил 'undefined' ..Я создал текущий объект всплывающего окна, чтобы иметь доступ к всплывающему окну в моих функциях handleSelected, но это больше не работает ...

У вас есть идеи?

...