谷歌地图 - 将InfoWindows附加到数组中的多边形

时间:2011-08-18 16:45:09

标签: javascript google-maps polygon infowindow

我整个早上一直用这个撞在墙上。我创建了一个多边形数组,并希望将每个将在infoWindow中显示的数据关联起来。我可以在地图上看到所有多边形。我添加了监听器,它会触发(颜色发生变化),但我没有得到infoWindow。任何帮助都会有很大的帮助!

干杯!

...ç

tmppoly = new google.maps.Polygon({
   map: map,
   paths: polypath,
   strokeColor: scolor,
   strokeOpacity: 0.5,
   strokeWeight: 2,
   fillColor: fcolor,
   fillOpacity: 0.5
});

addPolygonClick(tmppoly,mdata);
plot_polygons.push(tmppoly);

...

function addPolygonClick(poly,html) {

    infowindow = new google.maps.InfoWindow(
    { 
        content: html
    });

    google.maps.event.addListener(poly,'click', function(event) {
        this.setOptions({fillColor: "#000000"});
        infowindow.open(map);
    }); 

}

3 个答案:

答案 0 :(得分:8)

我可以就您的问题提供一些有用的建议。

首先,您应该知道关于方法'infowindow.open(map,anchor?:MVCObject)'的表达式。正如google api v3所说:在核心API中,唯一的锚是Marker类。 Polygon类与条件不匹配,但是,我们可以用另一种方式实现。

var polygon = new google.maps.Polygon({
    paths: PGpoints,   //The PGpoints is the collection of points around this polygon.
    map: map,
    strokeColor: colory,
    strokeOpacity: 0.6,
    strokeWeight: 1,
    fillColor: colory,
    fillOpacity: 0.35       
});

polygon.set("Info", idy);  // Set some attributes for adding extra information into this polygon.   

google.maps.event.addListener(polygon, 'click', function() {
    var infoWindow = new google.maps.InfoWindow();
    infoWindow.setContent("Information : " + polygon.get("Info"));

    // 'laty,lngy' is the location of one point in PGpoints, which can be chosen as you wish
    infoWindow.setPosition(new google.maps.LatLng(laty,lngy));     
    infoWindow.open(map);
});

上面的代码已通过测试,您可以直接使用它。然后,如果单击一个多边形,infoWindow将出现在地图上方。

答案 1 :(得分:2)

有一些问题可能导致无法正常工作:

<强> 1 你需要在infowindow前面加一个var,使它成为一个局部变量:

var infowindow = new google.maps.InfoWindow(...

实际上,每次添加新的点击监听器时都会替换infowindow变量。

<强> 2 您需要为infowindow指定位置或锚点(请参阅:http://code.google.com/apis/maps/documentation/javascript/reference.html#InfoWindowOptions)。

唯一有效的锚点是标记,因此您可能希望指定“位置”属性。 'position'必须是有效的google.maps.LatLng对象。我怀疑你会想要计算多边形的中心以用作位置。

您还需要确保map是一个全局变量,尽管它可能会查看您的其余代码。

答案 2 :(得分:0)

请查看此https://developers.google.com/maps/documentation/javascript/examples/event-closure并将其与上面的响应结合起来,为多边形数组中的每个多边形指定唯一的消息。

我还在一层中有多个多边形,每个多边形都有唯一的消息。我还没有成功。通过上面的响应,我得到了显示的信息窗口,但是我得到了所有多边形的相同消息。 一旦我解决了问题,我就会发布解决方案。