要从 HTML on click 函数运行,您的
showInfo
函数需要位于全局上下文中。
此外,如果您查看生成的 HTML,您将看到:
<a href="javascript:showInfo(-1)">Barcelona</a>
(-1 不是数组的有效索引)
并且
locations
数组是空的,你永远不会将标记推到它上面。
当我解决所有这些问题时,链接有效:更新的小提琴
代码片段:
var map;
var locations = [];
function showInfo(i) {
google.maps.event.trigger(locations[i], "click");
}
$(document).ready(function() {
var latlng = new google.maps.LatLng(11.610707, 122.740089);
var myOptions = {
zoom: 12,
center: latlng,
disableDefaultUI: true,
scaleControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
draggableCursor: 'move',
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow({
content: ""
});
var data = {
"markers": [{
"latitude": 11.606503,
"longitude": 122.712637,
"title": "Copenhagen"
}, {
"latitude": 11.585988,
"longitude": 122.757084,
"title": "Barcelona"
}
]
};
locations.length = 0;
for (p = 0; p < data.markers.length; p++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.markers[p].latitude, data.markers[p].longitude),
map: map,
draggable: false,
title: "marker " + p,
id: p
});
locations.push(marker);
$('#mapa').append('<li class=' + marker.id + '><a href="javascript:showInfo(' + (locations.length - 1) + ')">' + data.markers[p].title + '</a></li>');
bindInfoWindow(marker, map, infowindow, data.markers[p].title);
}
function bindInfoWindow(marker, map, infowindow, strDescription) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(strDescription);
infowindow.open(map, marker);
});
}
});
@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');
@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css');
.container {
margin-top: 30px;
}
#map_canvas {
width: 100%;
height: 400px;
}
.highlighted {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<ul id="mapa">
</ul>
<div class="container">
<div class="well">
<div id="map_canvas"></div>
</div>
</div>