如何使用谷歌地图API在标记上设置弹出窗口
How to set a popup on markers with Google Maps API?
我有这段代码,用于显示和设置所有标记。如何使用此代码添加带有标记信息的弹出窗口?我在文本上添加了"I"变量,但它在所有弹出的标记上设置了"test-723",其中723是"I"的最后一个值。怎么了?
for (var i = 0; i < arraylng.length-1; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arraylng[i], arraylat[i])
});
var infowindow = new google.maps.InfoWindow({
content: " "
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('test: ' + i + '');
infowindow.open(map, this);
});
markers.push(marker);
}
首先,将循环条件更改为i < arraylng.length
。现在它没有捕获数组的最后一个元素。
JavaScript变量使用函数范围,因此需要为每个标记侦听器调用一个函数来创建正确的变量引用。您可以使用匿名函数,如这里所示,或者定义一个用于创建点击侦听器的函数:
多信息窗口:
function makeInfoWindowEvent(map, infowindow, marker) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
很可能您不希望同时打开多个InfoWindow,因为必须单击关闭x会很烦人。然后,您只需要一个InfoWindow对象,并在单击标记时设置内容:
单一信息窗口:
...
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i < arraylng.length-1; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arraylng[i], arraylat[i]),
map: map
});
makeInfoWindowEvent(map, infowindow, "test" + i, marker);
markers.push(marker);
}
}
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
这是您可以添加弹出内容的区域
var infowindow = new google.maps.InfoWindow({
content: "Add your popup content here"
});
这是为了显示弹出的
marker.addListener('click', function() {
infowindow.open(map, marker);
});
下面的代码显示了它是如何工作和使用的。
features.forEach(function(feature) {
var infowindow = new google.maps.InfoWindow({
content: "Add your popup content here"
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,long),
icon: "image.png",
/*icon: icons[feature.type].icon,*/
title: "Title for marker",
map: map
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: myLatLng,
....
content: point[4]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
循环内的代码。这对我来说非常有效。
这是因为变量i
不在循环中使用,而是在单击标记时使用——然后i等于最后一个索引+1…addListener
是异步的,而不是同步的。
取下infowindow.setContent('test: ' + i + '');
,用content: 'test: ' + i
替换content: " "
。这应该可以解决你的问题。
相关文章:
- 如何在提交事件的底部设置窗口位置
- 如何保存和设置窗口.pageYOffset with shadowbox.js.
- 在 JavaScript Core iOS 7 中设置窗口
- 设置窗口弹出窗口坐标
- 从控制器设置窗口字段值
- 如何在网页中设置窗口标题
- ExtJ设置窗口高度
- 设置窗口.在IE8中未定义的onbeforeunload原因"未实现错误
- 设置窗口.位置vs.输入url
- 如何在javascript中设置窗口的本地路径.在c# .net中使用
- 设置窗口全屏(真正的全屏;F11功能)
- Javascript设置窗口的大小
- 我可以让SignalR在设置窗口位置时不断开连接吗?
- Adobe AIR应用程序在JavaScript中记住和设置窗口状态
- 设置窗口大小
- 使用window.Open在默认浏览器中打开链接,并在可可中的webView中设置窗口大小
- JavaScript 设置窗口选择
- 设置窗口的位置/jquery
- 使用链接设置窗口焦点
- JS - 使用当前窗口大小设置窗口高度