按钮在谷歌地图的infoWindow中不起作用



我有一个谷歌地图,它正在工作,我想在信息窗口上添加一个按钮,但不知怎么就不工作了。虽然函数已定义但仍会抛出错误http://jsfiddle.net/mpgxn53q/

<div id="apptMap"></div>
//the js code
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
var locations = [["158845-001 - Adas Israel Congregation",38.9369545,-77.0575097,1],["163888-137 - Construction LLC",43.1765812,-84.6986701,2.0],["163888-155 - Construction LLC",43.1765812,-84.6986701,3.0],["167176-007 - GLDB MTM10 GLR016",42.4894512,-95.5449508,4.0],["167195-003 - 91622 DB A4",42.8275053,-84.5717997,5.0],["167195-002 - 91622 DB A4",42.8275053,-84.5717997,6.0],["167176-005 - GLDB MTM10 GLR016",42.0023,-93.6110955,7.0],["167176-004 - GLDB MTM10 GLR016",42.0023,-93.6110955,8.0]];
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('apptMap'), {
zoom: 10,
center: new google.maps.LatLng(42.0023,-93.6110955),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {  
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>',
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
function mapsZoomMarker(wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
} 
init();

作用域有问题,正因为如此,您才编写了脚本。我不会重写你的剧本,但我会为你的确切情况提供解决方案。

您需要在全局范围(窗口对象(中定义函数mapsZoomMarker,如下所示:

window.mapsZoomMarker = function (wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
} 

还有一个错误,在点击标记时调用的函数中。当你为弹出窗口分配html时,如

content: this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>'

i变量已经设置为8,因此不使用this.id

content: this.html +'<button onclick="mapsZoomMarker('+this.id+')">Click me</button>'

这是最新的小提琴http://jsfiddle.net/rn27f05v/

我将提出一个我认为最适合您的解决方案。相反,您可以在var信息窗口中调用函数,只能定义一个变量来放置您想要的内容。

您可以将var信息窗口更改为:

var infowindow = new google.maps.InfoWindow({
id: this.id,
content: content, //here the variable that call your content
position:this.getPosition()
});

所以。。。在您的google.maps.event.addListener(markers[i], 'click', function(){...之上,您可以添加:

var content = '<button onclick="mapsZoomMarker('+i+')">Click me</button>';

通过这种方式,单击操作将起作用。

希望这条建议对你有所帮助。

最新更新