请您查看this demo并告诉我为什么我无法在链接点击上呈现关联的信息窗口? 如你所见,我已经尝试了
$('#mapa').append('<li class=' + marker.id + '><a href="javascript:showInfo(' + (locations.length - 1) + ')">' + data.markers[p].title + '</a></li>');
function showInfo(i) {
google.maps.event.trigger(locations[i], "click");
}
但我正在
未捕获的ReferenceError:未定义showInfo
当我点击链接时! 感谢
答案 0 :(得分:1)
要从单击函数的HTML运行,您的showInfo
函数需要位于全局上下文中。
另外,如果你看一下生成的HTML,你会看到:
<a href="javascript:showInfo(-1)">Barcelona</a>
( - 1不是数组的有效索引)
locations
数组为空,您永远不会将标记推到它上面。
当我解决所有这些问题时,链接有效:updated fiddle
代码段
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>