添加事件监听器:如何在typescript angular中添加偶数监听器?

时间:2017-11-13 12:17:54

标签: angular google-maps typescript addeventlistener

我正在使用google-maps,我正在显示一个标记点​​击我通过数据库获取的坐标。他们工作正常。但现在我想显示点击标记的地方标题,但我不知道在哪里放置事件监听器的代码。

以下是我的app.component.ts

app.comp.ts

import { AfterViewInit, Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ProductService } from './product.service';

declare var google: any;

// Islamabad Cordinates ===================================================
var myLatLng = { lat: 33.7294, lng: 73.0931 };

// Declaare Map  ==========================================================
var map;

// Markers array to push all marker ======================================
var markers = [];

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

  //define an array of products
  products = [];

  //constructor func
  constructor(private _productService: ProductService) { }

  //after constructor func this func runs , in which we are
  // accessing the class function getproducts and objects products
  // through this.
  // => means callback in which we are dumping data in products
  //array
  ngOnInit() {
    this._productService.getProducts()
      .subscribe(products => { this.products = products; console.log(this.products); })

  }

  ngAfterViewInit() {

    setTimeout(() => {
      map = new google.maps.Map(document.getElementById('map'), {
        center: myLatLng,
        zoom: 12
      });

      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: 'Hello World!'
      });

      markers.push(marker);
      console.log(map)

    }, 3000);
  }

  showMarker(latitude, longitude) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
    // TS convert string to Int using +
    var clickedLocation = { lat: +latitude, lng: +longitude }
    console.log(clickedLocation);

    map.panTo(clickedLocation);

    var marker = new google.maps.Marker({
      position: clickedLocation,
      map: map,
      title: 'Hello World!'
    });
  }
}

现在我应该把这段代码放在哪里?

     google.maps.event.addListener(marker, 'click', () => {
    console.log('hei');
  });

1 个答案:

答案 0 :(得分:1)

你可以写这段代码

google.maps.event.addListener(marker, 'click', () => {
    console.log('hei');
});

直接在

之后
var marker = new google.maps.Marker({...