Reputation: 49
When I hover over mouse then an InfoWindow should open saying "hello". However if I take cursor elsewhere it should close that InfoWindow. This is possible using the code below:
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent("Hello");
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
But if I click on the marker it should open the InfoWindow with different content in it. This is possible using the code below:
google.maps.event.addListener(marker, 'click',function() {
infowindow.setContent(mycontent(name,msg));
infowindow.open(map, marker);
});
Problem: If I click on the marker the InfoWindow opens with my content but as soon as cursor moves the InfoWindow closes due to mouseout event. How do we prevent this so that on click, InfoWindow remains open until and unless some one clicks on the cross (X) mark on InfoWindow?
Upvotes: 3
Views: 5774
Reputation: 161334
Set a flag (I'll call it clicked
) when the marker is clicked. Check that flag in the mouseover/mouseout listeners, don't take any action if it is set. Clear the flag (set it to false) when the InfoWindow is closed by clicking on the "X".
code snippet:
var infowindow = new google.maps.InfoWindow();
var clicked = false;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
google.maps.event.addListener(marker, 'mouseover', function() {
if (!clicked) {
infowindow.setContent("Hello");
infowindow.open(map, marker);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
if (!clicked) {
infowindow.close();
}
});
google.maps.event.addListener(marker, 'click', function() {
clicked = true;
infowindow.setContent("mycontent(name,msg)");
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow,
'closeclick',
function() {
clicked = false;
})
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Upvotes: 5