infowindows google maps v3有多个位置

时间:2014-11-27 22:20:46

标签: google-maps google-maps-api-3 infowindow

你好,我想在我标记的两个地方都有一个信息窗口。但我不知道该怎么做。我正在使用谷歌地图api v3。任何被回答的人都会非常沮丧。代码如下:

var locations = [
  ['Bondi Beach', 36.773861, -2.804269],
  ['Coogee Beach', 36.839467, -2.463484],
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 20,
scrollwheel: false,
  center: new google.maps.LatLng(-39.92, 151.25),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;
var markers = new Array();

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  markers.push(marker);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);

    }
  })(marker, i));
}



function AutoCenter() {
  //  Create a new viewpoint bound
  var bounds = new google.maps.LatLngBounds();
  //  Go through each...
  $.each(markers, function (index, marker) {
  bounds.extend(marker.position);
  });
  //  Fit these bounds to the map
  map.fitBounds(bounds);
}
AutoCenter();

1 个答案:

答案 0 :(得分:0)

当多个infowindows同时可见时,每个标记需要一个Infowindow实例

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    //store for each marker a infowindow
    infowin:new google.maps.InfoWindow({content:locations[i][0],
                                        preserveViewport:true,
                                        map:null})
  });

  markers.push(marker);

  google.maps.event.addListener(marker, 'click', function() {
      //open the infowindow
      this.get('infowin').open(this.getMap(), marker);

  });
  //trigger the marker-click to open the infowindow automatically
  google.maps.event.trigger(marker,'click',{});
}