[英]Javascript - Google Maps - Handing over a function to marker.addListener(
I had this code: 我有以下代码:
this.createMarker = function(lat, lng, string) {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(lat, lng),
visible: true,
});
marker.addListener('click', function() {
var contentstring = string;
var infowindow = new google.maps.InfoWindow({
content: contentstring
});
infowindow.open(map, marker);
setTimeout(function() {
infowindow.close();
}, 3000);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null)
}, 1400);
});
return marker;
}
createMarker is called when an array is build out of API results. 从API结果构建数组时将调用createMarker。
As I was using the infowindow and the marker animation in a different location in the code as well, I decided to encapsulate it: 当我也在代码的不同位置使用信息窗口和标记动画时,我决定将其封装:
this.clickMarker = function(string,map,marker) {
var contentstring = string;
var infowindow = new google.maps.InfoWindow({
content: contentstring
});
infowindow.open(map, marker);
setTimeout(function() {
infowindow.close();
}, 3000);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null)
}, 1400);
}
Now when I try to call the function in marker.addListener 现在,当我尝试在marker.addListener中调用该函数时
marker.addListener('click', this.clickMarker(string,map,marker));
the info windows and the marker animation load right when the map loads. 地图加载时,信息窗口和标记动画将立即加载。 The markers do not react to click after that.
之后,标记不会对单击做出反应。
I also tried this 我也尝试过
marker.addListener('click', function() {
this.clickMarker(string,map,marker);
});
But it gives me an error that clickMarker is not defined. 但这给我一个错误,即未定义clickMarker。 Not sure why marker.addListener('click', this.clickMarker(string,map,marker));
不确定为什么marker.addListener('click',this.clickMarker(string,map,marker)); does not work
不起作用
There are some ways you can solve this: 有几种方法可以解决此问题:
1.- Returning a function from clickMarker
. 1.-从
clickMarker
返回函数。
this.clickMarker = function(string,map,marker) {
return function() {
var contentstring = string;
var infowindow = new google.maps.InfoWindow({
content: contentstring
});
infowindow.open(map, marker);
setTimeout(function() {
infowindow.close();
}, 3000);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null)
}, 1400);
}
}
2.- Bind the this
value to the listener. 2.-将
this
值绑定到侦听器。
marker.addListener('click', function() {
this.clickMarker(string,map,marker);
}.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.