添加一个使用Google Maps信息窗操作的事件监听器

时间:2013-09-08 16:58:45

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

最长的时间我无法在我的网站的酒厂A-Z部分的链接中添加事件监听器(地图上方的绿色按钮):

http://www.michiganwinetrail.com/

问题在于我之前创建了一个非常复杂的循环

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

    locations[i][0] = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        title: locations[i][3],
        map: map,
        content: locations[i][4]
    });

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

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

}

当我点击葡萄酒厂A-Z部分中的链接时,我需要添加到此循环中以允许我的信息窗口弹出?如果可能的话,我想远离jquery

1 个答案:

答案 0 :(得分:0)

为位置数组中的位置创建唯一ID,如下所示:

var locations[0] = ['twoLads',44.932317,-85.492437, '2 Lads', twoLads_content];
var locations[1] =  ['belLago',44.8529,-85.7663, 'Bel Lago', belLago_content];
//etc...

现在,您可以为每个“Map It!”添加一个点击监听器。像这样的链接:

<tr class="rowClass">
<td>Bel Lago</td>
<td><a href="http://bellago.com/">Visit Website</a></td>
<td class="mapIt"><a onclick="openMarker(1);">Map It!</a></td>
</tr>

然后你可以定义一个函数来处理infoWindow的打开。

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

locations[i][0] = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    title: locations[i][3],
    map: map,
    content: locations[i][4]
});

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

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

}

window.openMarker = function(locationId){
    // Set content according to the locationId
    infowindow.setContent(locations[locationId][4]);
    // Open the infowindow at the location of the appropriate marker which gets stored in array key 0 in your loop above.
    infowindow.open(map, locations[locationId][0]);
}