Angular - добавить события на флажки - PullRequest
0 голосов
/ 22 мая 2018

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

Все компоненты карты находятся внутри файла app.component.ts, а мое меню с флажками - файл app.component.html.

app.component.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
  </head>

    <body>

      <div class="header">
          <mat-toolbar>OpenLayers</mat-toolbar>

          <div class="menu">
              <button mat-button [matMenuTriggerFor]="menu">Marqueurs</button>
              <mat-menu #menu="matMenu">
                <input type="checkbox" id="piscine" name="piscine" value="piscine">
                <label for="subscribeNews">Piscines</label>
                <br>
                <input type="checkbox" id="piscine" name="piscine" value="piscine">
                <label for="subscribeNews">Parkings</label>
              </mat-menu>
          </div>
      </div>

      <div id="map" class="map"></div>
          <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content"></div>
          </div>
    </body>
</html>

В моем app.component.ts у меня есть этот код для получения статуса флажка, но он не работает (этот код работает в простом HTML-файле)

app.component.ts: (извлечение)

$('#piscine').on('change', function() {
    var isChecked = $(this).is(':checked');
    if (isChecked) {
      this.map.addControl(this.vectorLayer_Piscine);
      this.vectorLayer_Piscine.setStyle(piscine);
      this.map.addOverlay(popup);
    } else {
      this.map.removeControl(this.vectorLayer_Piscine);
      this.map.removeOverlay(popup);
    }
  });

  $('#parking').on('change', function() {
    var isChecked = $(this).is(':checked');
    if (isChecked) {
      this.map.addControl(this.vectorLayer_Parking);
      this.vectorLayer_Parking.setStyle(markers);
      this.map.addOverlay(popup);
    } else {
      this.map.removeControl(this.vectorLayer_Parking);
      this.map.removeOverlay(popup);
    }
  });

С этим импортом для jQuery: import $ from 'jquery'; (Iused npm install jquery)

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

Есть ли другой способ получить статус флажка?

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

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 olProj from 'ol/proj';
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 proj from 'ol/proj';
import $ from 'jquery';

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

export class AppComponent implements OnInit {

  map: OlMap;
  layer1: OlWMS;
  layer2: OlWMS;
  layer3: OlWMS;
  layer: OlTileLayer;
  view: OlView;
  layerSwitcher: OlSwitch;
  WFS: WFS;
  vectorLayer_parking: VectorLayer;
  vectorLayer_piscine: VectorLayer;
  parkingLayer: VectorSource;
  piscineLayer: VectorSource;

  constructor() {
  }

  ngOnInit() {

    this.layer1 = new OlWMS({
      url: '...',
      params: {...},
      attributions: '...'
    });

    this.layer2 = new OlWMS({
      url: '...',
      params: {...},
      attributions: '...'
    });

    this.layer3 = new OlWMS({
      url: '...',
      params: {...},
      attributions: '...'
    });

    //view

    this.view = new OlView({
      center: [0, 0],
      minZoom: 11,
      maxZoom: 19,
      zoom: 12
    });

    this.parkingLayer = new VectorSource({
      url: '...',
      format: new GeoJSON()
    });

    this.piscineLayer = new VectorSource({
      url: '...',
      format: new GeoJSON()
    });

    this.vectorLayer_parking = new VectorLayer({
      source: this.parkingLayer
    });

    this.vectorLayer_piscine = new VectorLayer({
      source: this.piscineLayer
    });

    this.map = new OlMap({
      target: 'map',
      layers: [new Group({
        title: 'Fonds de carte',
        layers: [
          new OlTileLayer({
            title: 'Layer1',
            source: this.layer1,
            type: 'base'
          }),
          new OlTileLayer({
            title: 'Layer2',
            source: this.layer2,
            type: 'base'
          })
        ]
      }),
      new Group({
        title: 'Surcouche',
        layers: [
          new OlTileLayer({
            title: 'Layer3',
            source: this.layer3,
            format: new WFS(),
            visible: false
          })
        ]
      }),
      ],
      view: this.view
    });

    //popup

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

    var 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 = function() {
      popup.setPosition(undefined);
      closer.blur();
      return false;
    };

    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;
      popup.setPosition(coord);
    }
  });

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

    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' : '';
    });
  }
}

app.component.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
  </head>

    <body>

      <div class="header">
          <mat-toolbar>OpenLayers</mat-toolbar>

          <div class="menu">
              <button mat-button [matMenuTriggerFor]="menu">Marqueurs</button>
              <mat-menu #menu="matMenu">
                <input type="checkbox" id="piscine" name="piscine" (change)="handleSelected($event)">
                <label for="subscribeNews">Piscines</label>
                <br>
                <input type="checkbox" id="parking" name="parking">
                <label for="subscribeNews">Parkings</label>
              </mat-menu>
          </div>
      </div>

      <div id="map" class="map"></div>
          <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content"></div>
          </div>
    </body>
</html>
0 голосов
/ 22 мая 2018

Прежде всего, я мог видеть два

<input type="checkbox" id="piscine" name="piscine" value="piscine">

в вашем коде.Пожалуйста, исправьте его (идентификаторы и имена совпадают).

Далее не нужно указывать значение свойства.Удалите его.

Затем сделайте, как показано ниже

<input type="checkbox" id="piscine" name="piscine" (change)="handleSelected($event)">

и в файле ts,

handleSelected($event) {
   if ($event.target.checked === true) {
   // Handle your code
   }
}

Надеюсь, это поможет вам!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...