鼠标悬停,mouseout并点击谷歌地图上的相同标记

时间:2016-01-14 04:54:39

标签: javascript google-maps google-maps-markers

当我将鼠标悬停在鼠标上时,InfoWindow应该打开“hello”。但是,如果我将光标移到别处,它应该关闭InfoWindow。这可以使用以下代码:

google.maps.event.addListener(marker, 'mouseover', function() {
   infowindow.setContent("Hello");
   infowindow.open(map, marker);
});

google.maps.event.addListener(marker, 'mouseout', function() {        
   infowindow.close();
});

但是,如果我点击标记,它应该打开InfoWindow,其中包含不同的内容。这可以使用以下代码:

google.maps.event.addListener(marker, 'click',function() {        
   infowindow.setContent(mycontent(name,msg));
   infowindow.open(map, marker);          
});

问题:如果我点击标记,InfoWindow会打开我的内容,但是一旦光标移动,InfoWindow就会因mouseout事件而关闭。我们如何防止这种情况,以便在点击时,InfoWindow保持打开状态,直到并且除非有人点击InfoWindow上的十字(X)标记?

1 个答案:

答案 0 :(得分:2)

单击标记时设置一个标记(我将其称为clicked)。检查mouseover / mouseout侦听器中的该标志,如果已设置,则不执行任何操作。通过单击" X"来关闭InfoWindow时清除标志(将其设置为false)。

代码段



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"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;

相关问题