【问题标题】:Google Maps - Attaching InfoWindows to polygons in arrayGoogle Maps - 将 InfoWindows 附加到数组中的多边形
【发布时间】:2011-08-18 16:45:09
【问题描述】:

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

干杯!

C...

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);
    }); 

}

【问题讨论】:

  • 我相信 infowindow 需要一个位置选项或标记参数,除非他们更改它。

标签: javascript google-maps polygon infowindow


【解决方案1】:

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

首先,你应该知道'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 将出现在地图上方。

【讨论】:

  • 谢谢!这个解决方案真的很有帮助。
【解决方案2】:

有一些问题可能会阻止它工作:

1: 您需要在 infowindow 前面添加一个 var,使其成为局部变量:

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

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

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

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 如果你能提供一个如何组合它们的例子,这可能是一个更好的答案。
    最近更新 更多