从阵列中自动显示一个infowindow

时间:2013-11-22 15:43:09

标签: javascript google-maps infowindow

我有一个包含指针数组和infowindows数据的Google地图。我想在加载页面/地图时显示特定的信息窗口。

我该怎么做:

这是我的代码:

function initialize() {

var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
    center: new google.maps.LatLng(53.47921, -1.00201),
        mapTypeId: google.maps.MapTypeId.ROADMAP

};


map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
map.setTilt(45);

// Car Parks
var markers = [
    ['location 1', 53.47921, -1.00201],
    ['location 2', 53.50726,-1.04641],
    ['location 3', 53.48313,-1.01016],
    ['location 4', 53.48197,-1.00954],
    ['location 5', 53.48319,-1.00842]
];



var infoWindowContent = [
    ['<div class="info_content">' +
    '<strong>text 1' +    
    '</div>'],
    ['<div class="info_content">' +
    '<strong>text 2' +    
    '</div>'],
    ['<div class="info_content">' +
    '<strong>text 3' +    
    '</div>'],
    ['<div class="info_content">' +
    '<strong>text 4' +    
    '</div>'],
    ['<div class="info_content">' +
    '<strong>text 5' +    
    '</div>']
];

// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map  
for( i = 0; i < markers.length; i++ ) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
        position: position,
        map: map,
        title: markers[i][0]
    });

    // Allow each marker to have an info window 
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.open(map, marker);
        }
    })(marker, i));

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
    this.setZoom(13);
    google.maps.event.removeListener(boundsListener);
});

}

任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:0)

请参阅example at jsBin

我对您的示例进行了一些更改

  • 添加了样式,适当的高度和宽度
  • 缺少初始缩放级别
  • infoWindowContent现在只是字符串数组,标记已更正(</strong>缺失)
  • LatLngBounds():它需要SW和NE点。已更改为使用bounds.extend()
  • infoWindow现在在一个名为for loop
  • 的函数中创建

这是the 2nd example,它会在页面加载时打开第一个信息窗口。您可以将其更改为打开其中任何一个。