将Infowindow添加到每5秒刷新一次的数组标记Google地图

时间:2017-01-19 14:18:06

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

我已按照此示例(http://jsfiddle.net/upsidown/p646xmcr/)在地图上每5秒刷新一次标记的位置。现在我不明白我怎么能用一个不同的变量为每个标记添加一个infowindow而不是说时间和地理位置(或者只是beach数组的第5个元素)。

var map;
var markers = []; // Create a marker array to hold your markers
function initialize() {
    var mapOptions = {
        zoom: 5,
        center: new google.maps.LatLng(10,12),
        mapTypeId: google.maps.MapTypeId.SATELLITE
    }

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

    setMarkers(beaches);

    // Bind event listener on button to reload markers
    //document.getElementById('reloadMarkers').addEventListener('click', reloadMarkers);
}

var n = 0;
setInterval(function reloadMarkers() {
  n++;
  var beaches = [
        ['Bondi Beach', 10+n, 10+n, 5],
        ['Coogee Beach', 10-n, 11-n, 5],
        ['Cronulla Beach', 10-n, 12+n, 3],
        ['Manly Beach', 10+n, 13-n, 2],
        ['Maroubra Beach', 10, 14, 1]
    ];
    // Loop through markers and set map to null for each
    for (var i=0; i<markers.length; i++) {
        markers[i].setMap(null);
    }
    // Reset the markers array
    markers = [];
    // Call set markers to re-add markers
    setMarkers(beaches);

      var infowindow = new google.maps.InfoWindow({
        content: "infowindowstringg"
      });
    marker.addListener('click', function() {
        infowindow.open(map, marker);
      });

}, 5000);

function setMarkers(locations) {
    for (var i = 0; i < locations.length; i++) {
        var beach = locations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            animation: google.maps.Animation.DROP,
            title: beach[0],
            zIndex: beach[3]
        });
        google.maps.event.addListener(marker, 'click', )
        // Push marker to markers array
        markers.push(marker);
    }
}



initialize();

1 个答案:

答案 0 :(得分:0)

在SetMarkers()

中定义infowindow变量
  

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

这是addListener()

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

工作示例

http://jsfiddle.net/p646xmcr/413/