将信息窗口添加到谷歌地图

时间:2014-07-17 12:05:21

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

我无法在此谷歌地图上的标记添加信息窗口。我尝试了不同的方法,但我认为我将代码添加到错误的位置或调用错误的变量。谁能帮我吗?谢谢!

var beaches = [
    ['Bondi Beach', -33.890542, 151.274856, 1],
    ['Coogee Beach', -33.923036, 151.259052, 1],
    ['Cronulla Beach', -34.028249, 151.157507, 2],
    ['Manly Beach', -33.800101, 151.287478, 2],
    ['Maroubra Beach', -33.950198, 151.259302, 2]
];

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(-33.88, 151.28),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

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

var markers = [];

var i, newMarker;

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

    newMarker.category = beaches[i][3];
    newMarker.setVisible(false);

    markers.push(newMarker);
}

function displayMarkers(category) {
    var i;

    for (i = 0; i < markers.length; i++) {
        if (markers[i].category === category) {
            markers[i].setVisible(true);
        } else {
            markers[i].setVisible(false);
        }
    }
}

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

1 个答案:

答案 0 :(得分:0)

var markers = [];

function initialize() {

    var beaches = [
        ['Bondi Beach', -33.890542, 151.274856, 1],
        ['Coogee Beach', -33.923036, 151.259052, 1],
        ['Cronulla Beach', -34.028249, 151.157507, 2],
        ['Manly Beach', -33.800101, 151.287478, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 2]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(-33.88, 151.28),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

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

    for (var i = 0; i < beaches.length; i++) {

        var newMarker = new google.maps.Marker({
            position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
            map: map,
            title: beaches[i][0]
        });

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

        markers.push(newMarker);
    }
}

initialize();

我已将代码包装在init函数中。注意你的变量声明/范围。如果您有任何疑问,请告诉我。你距离它还不远......

JSFiddle demo