我有这个正在运行的Google地图,我想在信息窗口上添加一个无法正常工作的按钮。虽然功能已定义但仍会引发错误 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();
答案 0 :(得分:2)
合并范围存在问题,这是因为您编写脚本的方式。我不会重写您的脚本,但是会为您提供具体解决方案。
您需要像这样在全局范围(窗口对象)中定义函数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/
答案 1 :(得分:0)
我将提出一种我认为最适合您想要的解决方案。而是在var infowindow中调用函数,您只能定义一个变量以放置所需的内容。
您可以将var infowindow更改为:
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>';
这样,点击操作将起作用。
希望此技巧对您有所帮助。