我正在实现Google Maps API,我希望在模板首次呈现时打开第一个标记的InfoWindow,但仅当满足特定条件时才打开。
我有类似以下代码:
我有类似以下代码:
{% if project %}
//the following is automatically open the infowindow of the FIRST marker in the array when rendering the template
var infowindow = new google.maps.InfoWindow({
maxWidth:500
});
infowindow.setContent(markers[0].html);
infowindow.open(map, markers[0]);
{% endif %}
在Firefox或Internet Explorer 7中,这不会引发错误; 它做到了我想要的 - 但它似乎是错误的。我的文本编辑器正在警告/错误中尖叫。
这是不好的编码实践吗?如果是,有替代建议吗?
这是完整的代码,在脚本标记内,并编辑掉了不相关的部分:
function initialize() {
...
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var markers = []
setMarkers(map, projects, locations, markers);
...
}
function setMarkers(map, projects, locations, markers) {
for (var i = 0; i < projects.length; i++) {
var project = projects[i];
var address = new google.maps.LatLng(locations[i][0],locations[i][1]);
var marker = new google.maps.Marker({
map: map,
position:address,
title:project[0],
html: description
});
markers[i] = marker;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.html);
infowindow.open(map,this);
});
}
{% if project %}
//the following is automatically open the infowindow of the FIRST marker in the array when rendering the template
var infowindow = new google.maps.InfoWindow({
maxWidth:500
});
infowindow.setContent(markers[0].html);
infowindow.open(map, markers[0]);
{% endif %}
})
}
google.maps.event.addDomListener(window, 'load', initialize);