[英]InfoWindow doesn't want to close with Google Maps Api V3
i can't close the info window of the marker i'm dragging, any idea ? 我无法关闭要拖动的标记的信息窗口,知道吗? Thanks for your help 谢谢你的帮助
function mapClick(event) {
createLocationMarker(event.latLng);
}
function createLocationMarker(location) {
var clickedLocation = new google.maps.LatLng(location)
var gMarker = new google.maps.Marker({position:location, map:gMap2, draggable: true});
gMap2.setCenter(location);
displayMarkerPosition(gMarker);
google.maps.event.addListener(gMarker, "dragstart", closeMapInfoWindow );
google.maps.event.addListener(gMarker, "dragend", function() { displayMarkerPosition(gMarker); });
}
function closeMapInfoWindow() {infowindow.close(); }
function displayMarkerPosition(gMarker) {
var message = "my message";
var infowindow = new google.maps.InfoWindow(
{ content : message,
});
infowindow.open(gMap2,gMarker);
}
Yes, you define infowindow
in a private scope, but access it outside that scope. 是的,您可以在私有作用域中定义infowindow
,但可以在该作用域之外访问它。 Add this to the beginning of your script: 将此添加到脚本的开头:
var infowindow;
And remove 'var ' from your constructor line: 并从构造函数行中删除“ var”:
infowindow = new google.maps.InfoWindow(
The finished code (from your sample) would look like this . 完成的代码(来自您的示例)将如下所示 。
A little more background 多一点背景
When you define a variable with var
, it is tied to that scope. 当您使用var
定义变量时,该变量将绑定到该范围。 If you define it in a function, only that function and other functions defined in it can access the variable. 如果在函数中定义它,则只有该函数和其中定义的其他函数才能访问该变量。 The only other way to pass it around is as a parameter in a function. 传递它的唯一其他方法是作为函数中的参数。
Update I would do this to facilitate multiple infowindows. 更新我这样做是为了促进多个信息窗口。 Notice I have reverted to the original var
declaration to keep it scoped to that function. 注意,我已恢复为原始的var
声明,以使其范围限于该函数。 I then return the reference to the object to use it later: 然后,我将引用返回给该对象以供以后使用:
function mapClick(event) {
createLocationMarker(event.latLng);
}
function createLocationMarker(location) {
var clickedLocation = new google.maps.LatLng(location)
var gMarker = new google.maps.Marker({position:location, map:gMap2, draggable: true});
gMap2.setCenter(location);
// Store reference to info window
var info = displayMarkerPosition(gMarker);
google.maps.event.addListener(gMarker, "dragstart", function(){ info.close } );
google.maps.event.addListener(gMarker, "dragend", function() { displayMarkerPosition(gMarker); });
}
function displayMarkerPosition(gMarker) {
var message = "my message";
var infowindow = new google.maps.InfoWindow(
{ content : message }
);
infowindow.open(gMap2,gMarker);
return infowindow; // Return the reference to the infowindow
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.