forEachFeatureAtPixel не срабатывает при использовании пользовательской функции - PullRequest
0 голосов
/ 30 октября 2019

Я пишу компонент в angular 8, который отображает карту открытой карты улиц с библиотекой ol (5.3.3), которая отображает ряд маркеров. Каждый маркер должен быть кликабельным, и в функции обратного вызова я должен получить его идентификатор. Я следовал коду, предложенному различными онлайн-решениями, но ни один не работает. В частности, функция forEachFeatureAtPixel всегда отвечает неопределенным.

Я пытался использовать как маркеры, так и функции, в обоих случаях функция o не нажимала кнопку или функция forEachFeatureAtPixel

import {Component, OnInit, AfterViewInit} from '@angular/core';
import Map from 'ol/Map';
import XYZ from 'ol/source/XYZ';
import {Tile, Vector} from 'ol/layer.js';
import View from 'ol/View';
import Marker from 'ol/Feature';
import Point from 'ol/geom/Point.js';
import {fromLonLat} from 'ol/proj.js';
import VectorSource from 'ol/source/Vector.js';
import {Icon, Style} from 'ol/style.js';
import Feature from 'ol/Feature';


@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit, AfterViewInit {
  map: any;
  feature: any

  constructor() {
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.map = new Map({
      target: 'map',
      layers: [
        new Tile({
          source: new XYZ({
            url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
          })
        })
      ],
      view: new View({
        center: [0, 0],
        zoom: 3,
        minZoom: 3,
        maxZoom: 15
      })
    })
    const marker = new Feature({
      geometry: new Point(fromLonLat([41.9, 12.5])),
      id: 'pippo'
    })
    marker.setStyle(
      new Style({
        image: new Icon(({
          crossOrigin: 'anonymous',
          src: '/assets/icons/marker-green.png',
          imgSize: [24, 24]
        }))
      })
    );
    const markerList = new Vector({
      source: new VectorSource({
        features: [
          marker
        ]
      })
    })
    this.map.addLayer(markerList);
    this.map.on('click', (event) => {
      this.feature = event.map.forEachFeatureAtPixel(event.pixel,
        function (feature) {
          return feature;
        });
      if (this.feature) {
        console.log(this.feature.getGeometry().getCoordinates());
      }
    })
  }
}

or 
import {Component, OnInit, AfterViewInit} from '@angular/core';
import Map from 'ol/Map';
import XYZ from 'ol/source/XYZ';
import {Tile, Vector} from 'ol/layer.js';
import View from 'ol/View';
import Marker from 'ol/Feature';
import Point from 'ol/geom/Point.js';
import {fromLonLat} from 'ol/proj.js';
import VectorSource from 'ol/source/Vector.js';
import {Icon, Style} from 'ol/style.js';
import Feature from 'ol/Feature';


@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit, AfterViewInit {
  map: any;
  feature: any

  constructor() {
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.map = new Map({
      target: 'map',
      layers: [
        new Tile({
          source: new XYZ({
            url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
          })
        })
      ],
      view: new View({
        center: [0, 0],
        zoom: 3,
        minZoom: 3,
        maxZoom: 15
      })
    })
    const marker = new Feature({
      geometry: new Point(fromLonLat([41.9, 12.5])),
      id: 'pippo'
    })
    marker.setStyle(
      new Style({
        image: new Icon(({
          crossOrigin: 'anonymous',
          src: '/assets/icons/marker-green.png',
          imgSize: [24, 24]
        }))
      })
    );
    const markerList = new Vector({
      source: new VectorSource({
        features: [
          marker
        ]
      })
    })
    this.map.addLayer(markerList);
    this.map.on('click', (event) => {
      this.feature = this.map.forEachFeatureAtPixel(event.pixel,
        function (feature) {
          return feature;
        });
      if (this.feature) {
        console.log(this.feature.getGeometry().getCoordinates());
      }
    })
  }
}

Iнет ошибки консоли. Я ожидаю как-то восстановить идентификатор маркера по щелчку. Исходя из кода, найденного в Интернете, я ожидаю, что решение будет предоставлено forEachFeatureAtPixel, но оно не работает.

...