Angular 9 和谷歌地图标记点击事件无法正常工作
Posted
技术标签:
【中文标题】Angular 9 和谷歌地图标记点击事件无法正常工作【英文标题】:Angular 9 & google map marker click event not working proprly 【发布时间】:2020-12-20 13:24:28 【问题描述】:下面是我启动地图并添加集群和标记的代码。一切正常,但标记点击的行为很奇怪,就像事件被立即触发并命中 API 一样,但全局变量会在几秒钟后更新,有时几分钟后更新。
renderMap()
window['initMap'] = () =>
this.loadMap();
;
if (!window.document.getElementById('google-map-script'))
const s = window.document.createElement('script');
s.id = 'google-map-script';
s.type = 'text/javascript';
s.src = 'https://maps.googleapis.com/maps/api/js?key=' + environment.GOOGLE_MAP_API_KEY + '&callback=initMap';
window.document.body.appendChild(s);
else
this.loadMap();
loadMap()
const map = new window['google'].maps.Map(this.mapElement.nativeElement,
center: lat: this.center.lat, lng: this.center.lng,
zoom: this.zoom
);
const markers = this.markers.map((location, i) =>
const marker = new google.maps.Marker(
position: lat: location.lat, lng: location.lng,
label: location.label,
icon: 'assets/img/marker_.png',
title: location.title,
clickable: true
);
marker.addListener('click', () =>
const m = location;
this.customer = m;
this.showLocation = true;
this.loading = true;
this.center =
lat: m.lat,
lng: m.lng
;
this.companyService.company(m.company_id).subscribe((company: any) =>
this.company = company;
this.loading = false;
, error =>
this.loading = false;
console.log(error);
);
);
return marker;
);
const markerCluster = new MarkerClusterer(map, markers,
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m');
ngOnInt()
this.renderMao();
【问题讨论】:
【参考方案1】:您可能需要在 NgZone 中运行 click
回调
constructor(private zone: NgZone)
marker.addListener('click', () =>
this.zone.run(() =>
...
);
【讨论】:
以上是关于Angular 9 和谷歌地图标记点击事件无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 和谷歌地图:foreach 纬度/经度显示标记或地图
为啥不从谷歌地图标记上的点击事件中调用 navigator.getCurrentPosition (function (position) )