标记内容(infoWindow)谷歌地图

时间:2011-05-03 11:40:32

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

我正在尝试将infoWindow添加到Google地图上的多个标记中。我最接近的是让infoWindow在所有标记上显示数组中可以看到的最后一个地址。我在下面粘贴的代码不起作用,我得到一个“Uncaught TypeError:无法读取未定义的属性'4'”。我确定这是一个范围问题,但我在这里绕圈子可以做一些帮助:

var hotels = [
            ['ibis Birmingham Airport', 52.452656, -1.730548, 4, 'Ambassador Road<br />Bickenhill<br />Solihull<br />Birmingham<br />B26 3AW','(+44)1217805800','(+44)1217805810','info@ibisbhamairport.com','http://www.booknowaddress.com'],
            ['ETAP Birmingham Airport', 52.452527, -1.731644, 3, 'Ambassador Road<br />Bickenhill<br />Solihull<br />Birmingham<br />B26 3QL','(+44)1217805858','(+44)1217805860','info@etapbhamairport.com','http://www.booknowaddress.com'],
            ['ibis Birmingham City Centre', 52.475162, -1.897208, 2, 'Ladywell Walk<br />Birmingham<br />B5 4ST','(+44)1216226010','(+44)1216226020','info@ibisbhamcity.com','http://www.booknowaddress.com']
        ];

        for (var i = 0; i < hotels.length; i++) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(hotels[i][1], hotels[i][2]),
                map: map,
                icon: image,
                title: hotels[i][0],
                zIndex: hotels[i][2]
            });

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

            google.maps.event.addListener(marker, 'click', function () {
                var markerContent = hotels[i][4];
                infoWindow.setContent(markerContent);
                infoWindow.open(map, this);
            });
        }

感谢您的期待。

2 个答案:

答案 0 :(得分:49)

我们已经解决了这个问题,虽然我们认为在for之外的addListener没有任何区别,但似乎。这是答案:

创建一个新函数,其中包含infoWindow的信息:

function addInfoWindow(marker, message) {

            var infoWindow = new google.maps.InfoWindow({
                content: message
            });

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.open(map, marker);
            });
        }

然后使用数组ID和要创建的标记调用该函数:

addInfoWindow(marker, hotels[i][3]);

答案 1 :(得分:32)

虽然这个问题已经得到解答,但我认为这种方法更好: http://jsfiddle.net/kjy112/3CvaD/在StackOverFlow google maps - open marker infowindow given the coordinates上提取此问题:

每个标记都有一个“infowindow”条目:

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}