谷歌地图v3:向圆形添加信息窗口

19

如何在使用google.maps.Circle创建的圆中添加InfoWindow?

例如:

var circ = new google.maps.Circle({
            center:latlng,
            clickable:false,
            fillColor:colors[count],
            fillOpacity:0.3, 
            map:map,
            radius:radius,
            strokeColor:colors[count],
            strokeOpacity:0.3});

//create info window
var infoWindow= new google.maps.InfoWindow({
    content: "Your info here"
    });

//add a click event to the circle
google.maps.event.addListener(circ, 'click', function(){
//call  the infoWindow
infoWindow.open(map, circ);
}); 

或者,是否有一种方法可以在圆的中心创建一个不可见的标记,以便单击该标记来访问infoWindow。


或者有没有一种方法可以在圆形中心创建一个不可见的标记,以便单击该标记来访问信息窗口? - trs
3个回答

45
你可以为你的圆形覆盖物添加信息窗口。但是你需要稍微调整一下你的代码。
首先,必须将clickable=true设置为你的圆形覆盖物(否则圆形上的点击事件不会被处理)。
然后,你需要更改点击监听器的代码。将圆形作为open()函数的参数没有效果(Circle不是MVCObject的正确类型,请阅读InfoWindow.open()函数的文档进行解释)。要显示信息窗口,你需要提供它的位置-例如点击事件的位置、圆形的中心等。
代码如下:
google.maps.event.addListener(circ, 'click', function(ev){
    infoWindow.setPosition(ev.latLng);
    infoWindow.open(map);
});

或者

google.maps.event.addListener(circ, 'click', function(ev){
    infoWindow.setPosition(circ.getCenter());
    infoWindow.open(map);
});

回复您的评论:您可以使用不可见标记创建一个把(只需将完全透明的图像作为标记图标),但我更喜欢使用圆形叠加层的解决方案。


ev 代表什么?是否有一种方法可以向用户指示点击圆圈,就像在标记中的“标题”选项一样? - trs
ev是MouseEvent(http://code.google.com/apis/maps/documentation/javascript/reference.html#MouseEvent)。圆形覆盖物没有任何文本指示器。但是当clickable为true时,光标在圆形上方时会发生变化。创建文本指示器并不那么简单 - 我会使用自定义覆盖物和圆形的mouseover事件监听器来实现这样的功能。 - Tomik
我尝试过这种方法,但它没有起作用。我收到了点击事件,但是我无法打开信息窗口!你有其他提示吗? - Future2020
只是想说,如果你正在循环中生成圆形,则应该使用“infoWindow.setPosition(this.getCenter());”而不是“infoWindow.setPosition(circ.getCenter());”。否则,信息窗口将始终弹出循环中的最后一个圆。 - Richard Williams
仅适用于圆的最后一个经纬度。我有一个经纬度数组并生成了几个圆。如何确定每个圆的内容? - zira
更新:我已经在http://stackoverflow.com/questions/16538075/adding-info-windows-to-multiple-circle-overlays找到了解决方案。=) - zira

2

在鼠标点击的位置设置信息窗口

google.maps.event.addListener(circ, 'click', function(ev){
    infoWindow.setPosition(ev.latLng); //<-- ev matches what you put ^ (mouse event)
    infoWindow.open(map);
});

0

我有同样的困惑。我用以下代码简单解决了它:

const circle = new google.maps.Circle({ strokeColor: "#FFFF00", strokeOpacity: 0.8, strokeWeight: 1, fillColor: "#FFFF00", fillOpacity: 0.4, center: position, // { lat: 46.021667, lng: 11.124717 } radius: distance, map: map,

    });

    const info = "Radius: " + circle.getRadius() + "m";
    const iw = new google.maps.InfoWindow({
        content: info,
        position: position,
    });
    circle.addListener("mouseover", () => {
        iw.open({
            map,
        });
    });
    circle.addListener("mouseout", () => {
        iw.close();
    });
    circle.addListener("click", () => {
        circle.setMap(null);
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接