Google 地图标记点击事件未在 Angular 组件中触发

问题描述 投票:0回答:1

我正在开发一个 Angular 应用程序,我需要在 Google 地图上显示车辆,并在单击相应标记时在模式中显示有关车辆的详细信息。但是,标记上的单击事件似乎没有触发,并且控制台中没有显示任何错误。我使用 Angular 和 NgRx 库来管理状态和处理异步数据。这是我的代码的相关部分:

import { Component, NgZone, ChangeDetectorRef } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { interval } from 'rxjs';
import { getVehicles } from 'src/app/shared/store/actions/vehicles.actions';
import { selectVehiclesList } from 'src/app/shared/store/selectors/vehicles.selectors';
import { IAppState } from 'src/app/shared/store/state/app.state';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {
  selectedVehicle: any;
  vehiclesList = [];
  map: google.maps.Map;

  constructor(private store$: Store<IAppState>, private zone: NgZone, private cdr: ChangeDetectorRef) {
    this.store$.dispatch(getVehicles());
  }

  ngOnInit() {
    this.vehicles.subscribe(vehicles => {
      this.vehiclesList = vehicles;
      this.updateVehicleMarkers(vehicles);
    });

    const mapProperties = {
      center: new google.maps.LatLng(20.6083796, -103.417235),
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(document.getElementById('map'), mapProperties);
  }

  updateVehicleMarkers(vehicles) {
    vehicles.forEach(vehicle => {
      const position = new google.maps.LatLng(vehicle.estado_vehiculo.ubicacion.latitude, vehicle.estado_vehiculo.ubicacion.longitude);
      const marker = new google.maps.Marker({
        position: position,
        map: this.map,
        title: vehicle.nombre,
        icon: './assets/car_icon.png',
        clickable: true
      });

      marker.addListener('click', () => {
        this.zone.run(() => {
          this.selectedVehicle = vehicle;
          this.cdr.detectChanges();
          console.log("Vehículo seleccionado: ", this.selectedVehicle);
        });
      });
    });
  }
}

当我单击标记时,指示所选车辆的预期控制台日志不会出现。我尝试过使用 Angular 的 NgZone 来确保检测到更改,但它仍然不起作用。可能是什么原因导致此问题以及如何解决它?

angular google-maps ngzone
1个回答
0
投票

你可以尝试

google.maps.event.addListener
吗?

  updateVehicleMarkers(vehicles) {
    vehicles.forEach(vehicle => {
      const position = new google.maps.LatLng(vehicle.estado_vehiculo.ubicacion.latitude, vehicle.estado_vehiculo.ubicacion.longitude);
      const marker = new google.maps.Marker({
        position: position,
        map: this.map,
        title: vehicle.nombre,
        icon: './assets/car_icon.png',
        clickable: true
      });

      google.maps.event.addListener(marker, 'click', () => { // <- changed here!
          this.selectedVehicle = vehicle;
          this.cdr.detectChanges();
          console.log("Vehículo seleccionado: ", this.selectedVehicle);
      });
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.