InfoWindow closeclick event in GoogleMaps V3 being fired too soon?
I am noticing that the closeclick
event on InfoWindow is being called prior to InfoWindow display in Google Maps V3. Has anyone else seen this? Bug? My misunderstanding of design?
Consider the simple example:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas {
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"
>
</script>
<script type="text/javascript">
function initialize()
{
var newLatLng = new google.maps.LatLng(47.620513,-122.33963);
var myOptions = { zoom: 12,
center: newLatLng,
draggingCursor: 'pointer',
draggableCursor: 'default',
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map( document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location)
{
// Create new marker
var marker = new google.maps.Marker({
position: location,
map: map
});
map.panTo(location);
markerWindow(marker);
}
// Prompt new event marker form
function markerWindow(marker)
{
var infoHtml = "testing";
var infoW = new google.maps.InfoWindow({});
infoW.setContent(infoHtml);
google.maps.event.addListener(infoW, 'closeclick', closeMarker());
infoW.open(map, marker);
}
function closeMarker()
{
window.alert("closeclick fired");
}
</script>
</head>
<body onload='initialize()'>
<div id="map_canvas" style=" position:absolute;
width:400px;
height:400px;"
>
</div>
</body>
</html>
If you run this example, closeclick
will be called prior to the displaying of the InfoWindow, not after it's creation and upon pressing the 'x' button in the upper right hand corner of the InfoWindow bubble. Is this is a bug (theirs or mine) or am I misunderstanding the design/use?
Environment: Windows 开发者_开发百科Vista (32-bit), Firefox 3.6.10
Guessing you might have solved this yourself already but for others with the same problem. Try passing the function as a reference instead. So instead of this:
google.maps.event.addListener(infoW, 'closeclick', closeMarker());
Do this:
google.maps.event.addListener(infoW, 'closeclick', closeMarker);
Note that your code resembles this:
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
But the anonymous function(event)
is a special case where it is "allowed" to use () after the function name.
You can also add the listener to the infowindow
itself.
Here an example inspired from Google Maps Javascript Documentation:
let contentString=
'<div id="content">' +
'<div id="siteNotice">' +
"</div>" +
'<h1 id="firstHeading" class="firstHeading">Hello World !</h1>' +
'<div id="bodyContent">' +
"<p><b>
精彩评论