Angular - 在复选框上添加事件

时间:2018-05-22 06:34:28

标签: javascript jquery angular openlayers

我使用OpenLayers使用Angular编程地图应用程序,我想在复选框上添加一些事件。我创建了一个mat-button,里面有一个包含两个复选框的mat-menu。

所有地图组件都在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';(我使用npm install jquery

使用此代码,我只想在检查相应的复选框时在地图上显示一些标记。

还有另一种检索复选框状态的方法吗?

2 个答案:

答案 0 :(得分:3)

首先,我可以看到两个

<input type="checkbox" id="piscine" name="piscine" value="piscine">
你的代码中的

。请更正它(ID和名称相同)。

接下来是不需要价值属性。删除它。

然后按以下步骤

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

并在ts文件中,

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

希望这会对你有帮助!

答案 1 :(得分:0)

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>