我正在开发一个带有角度6的网络应用程序。我整合了谷歌地图,但标记点击事件让我错了。
请提前帮助我。
import { } from '@types/googlemaps';
@ViewChild('whereMap') gmapElement: any;
map: google.maps.Map;
marker: google.maps.Marker;
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
let marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
}
地图已初始化且标记工作正常,但我无法触发点击事件。 我在ngOnInit()中调用了initMapp()。
答案 0 :(得分:0)
navigator.geolocation.getCurrentPosition
是异步的,您很可能遇到竞争条件。您应该在地理定位回调中移动google.maps.event.addListener
,否则您可以在创建标记元素之前尝试分配事件侦听器。
Google Maps JavaScript API错误消息ERROR TypeError: Cannot read property '__e3_' of undefined
通常意味着您尝试将事件分配给不存在的DOM元素。
尝试以下
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
我希望这有帮助!