Google Maps API Version3 infoWindow

Google Maps API Version3 の infoWindow についてです。

  • 1. マーカーをクリックした時に、他の infoWindow が閉じるようにしたい
  • 2. infoWindow に表示する内容を個別に指定したい
  • 3. ある程度 infoWindow のサイズをコントロールしたい

という要件があり、色々やってみたところなんとかできました。

忘れないようにメモです :mrgreen:

まずは地図の表示です。

...色々...
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="gmap" style="width:500px; height:500px;"></div>
<script type="text/javascript">
      var latlng = new google.maps.LatLng(35.710126,139.810665);
      var myOptions = {
          zoom: 10,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("gmap"), myOptions);
つづく...

次にマーカーと各マーカー用の infoWindow の指定です。

...つづき
var infoWindow;
var content;
 
//marker1
var myLatLng1 = new google.maps.LatLng(35.810126, 139.610665);
var marker1 = new google.maps.Marker({
    position: myLatLng1,
    map: map
});
google.maps.event.addListener(marker1, 'click', function() {
    if (infoWindow) infoWindow.close();
    infoWindow = new google.maps.InfoWindow({
        content: '<div style="width:200px;height:100px;"><p>マーカー1</p></div>'
        })
    infoWindow.open(map, marker1);
});
 
//marker2
var myLatLng2 = new google.maps.LatLng(35.710126, 139.610665);
var marker2 = new google.maps.Marker({
    position: myLatLng2,
    map: map
});
google.maps.event.addListener(marker2, 'click', function() {
    if (infoWindow) infoWindow.close();
    infoWindow = new google.maps.InfoWindow({
        content: '<div style="width:200px;height:100px;"><p>マーカー2</p></div>'
        })
    infoWindow.open(map, marker2);
});
 
//marker3
var myLatLng3 = new google.maps.LatLng(35.710126, 139.810665);
var marker3 = new google.maps.Marker({
    position: myLatLng3,
    map: map
});
google.maps.event.addListener(marker3, 'click', function() {
    if (infoWindow) infoWindow.close();
    infoWindow = new google.maps.InfoWindow({
        content: '<div style="width:200px;height:100px;"><p>マーカー3</p></div>'
        })
    infoWindow.open(map, marker3);
});
</script>