我有用于向交互式Google地图添加多个标记的脚本。我希望所有标记都能容纳不同的信息

时间:2012-03-05 08:28:49

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

我已经在下面创建了代码。此代码会生成包含不同标记的Google地图。我似乎没有得到正确的代码,因此每个标记将在鼠标点击显示不同的信息窗口。有没有办法在for循环中添加代码,以便所有标记都是使用不同的infowindows构建的,具有不同的内容?

<body onload="initialize()">

  <div id="map_canvas" style="width: 800px; height: 500px;"></div>

  <script type="text/javascript">
    function initialize() {
      var myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(23.241346, 18.281250),
      mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map_canvas"),
                                    myOptions);

      setMarkers(map, locations);
    }

     var locations = [
       ['AU', -37.850565, 144.980289 , 4],
       ['AS', 48.1670845, 16.3465254, 5],
       ['BE', 50.8826906, 4.4570261, 3],
       ['BR', -23.5004937, -46.8482093, 2],
       ['CZ', 50.0878114, 14.4204598, 1],
       ['DM', 55.6710507, 12.4401635, 6],
       ['FI', 60.2101064, 24.8251788, 7],
       ['FR', 48.8744779, 2.1668675, 8],
       ['GE', 51.19423, 6.70568, 9],
       ['GR', 38.0433281, 23.797971, 10]
     ];

     function setMarkers(map, locations) {
       var image = new google.maps.MarkerImage('punaise.png',
         new google.maps.Size(30, 30),
         new google.maps.Point(0,0),
         new google.maps.Point(0, 32));
       var shadow = new google.maps.MarkerImage('schaduw.png',
         new google.maps.Size(30, 30),
         new google.maps.Point(0,0),
         new google.maps.Point(0, 32));

       var shape = {
         coord: [1, 1, 1, 20, 18, 20, 18 , 1],
         type: 'poly'
       };

       for (var i = 0; i < locations.length; i++) {
         var entity = locations[i];
         var myLatLng = new google.maps.LatLng(entity[1], entity[2]);
         var marker = new google.maps.Marker({
           position: myLatLng,
           map: map,
           shadow: shadow,
           icon: image,
           shape: shape,
           title: entity[0],
           zIndex: entity[3],
         });
       }
    }
  </script>

1 个答案:

答案 0 :(得分:0)

这是相对直截了当的;在你的for循环中你想要初始化信息窗口,如:

for (var i = 0; i < locations.length; i++) {
    var entity = locations[i];
    var myLatLng = new google.maps.LatLng(entity[1], entity[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: entity[0],
        zIndex: entity[3],
    });
    infoWindow = new google.maps.InfoWindow({
        content: document.getElementById("overlayContent" + [i]).innerHTML
    });
}

overlayContent[i]会获得<div>(或其他元素)id overlayContent1等。然后在for循环之外添加一个点击处理程序,打开正确的信息窗口:

google.maps.event.addListener(marker, "click", function () {

    if (currentInfoWindow) {
        currentInfoWindow.close();
    }
    infoWindow.open(gmap, marker);
    currentInfoWindow = infoWindow;
});

currentInfoWindow检查确保一次只打开一个叠加层