我正在寻找使用我的Ionic 2/Angular 2应用程序实现GoogleMap.OnInfoWindowClickListener的语法。我想重定向到一个新页面,即当用户单击谷歌地图内的信息窗口时,将新页面推送到 NavController 上的堆栈。
我已经能够使用以下代码设置标记:
//Creates the event listener for clicking the marker and places the marker on the map
google.maps.event.addListener(marker, 'click', (function(marker, markerCount) {
return function() {
infowindow.setContent(htmlMarkupForInfoWindow);
infowindow.open(this.map, marker);
}
})(marker, this.markerCount));
不幸的是,信息窗口内容中的函数调用丢失了对"this"的引用,从而导致错误。任何帮助不胜感激!
这可能很笨拙,但它似乎有效...张贴了整个方法供参考。大部分代码基于 Josh Morony (https://www.joshmorony.com/( 提供的示例
这允许我在本地调用一个函数,传入与信息窗口关联的位置。infoWindow 的内容包装在类名为"content"的div 中。
addMarkerToMap(location, htmlMarkupForInfoWindow){
var infowindow = new google.maps.InfoWindow();
var myLatLng = new google.maps.LatLng(location.latitude, location.longitude);
var marker = new google.maps.Marker({
position: myLatLng,
map: this.map,
icon: this.mapIcon,
animation: google.maps.Animation.DROP,
});
//Gives each marker an Id for the on click
this.markerCount++;
this.infoWindows.push(infowindow);
let self = this;
//Creates the event listener for clicking the marker and places the marker on the map
google.maps.event.addListener(marker, 'click', ((marker, markerCount) => {
return () => {
self.hideAllInfoWindows();
infowindow.setContent(htmlMarkupForInfoWindow);
infowindow.open(this.map, marker);
}
})(marker, this.markerCount));
// add listener that will capture the click event of the infoWindow
google.maps.event.addListener(infowindow, 'domready', () => {
document.getElementById('content').addEventListener('click', () => {
self.onLocationSelected(location);
}, false);
});
}
如果有人有更简单的方法,请随时发表评论。
更改内部函数以使用Arrow function
,这有助于this
函数内部可用。
//Creates the event listener for clicking the marker and places the marker on the map
google.maps.event.addListener(marker, 'click', ((marker, markerCount) => {
return () => {
infowindow.setContent(htmlMarkupForInfoWindow);
infowindow.open(this.map, marker);
}
})(marker, this.markerCount));