如何在 google.maps.Circle 上使用 GoogleMaps InfoWindow()?

How to use GoogleMaps InfoWindow() on a google.maps.Circle?

如果我在循环中使用它,则不会显示信息窗口。

以下是如何将其与标记一起使用的示例: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/infowindow-simple

我做了类似的,但使用 Circle,下面的代码,如您所见,console.log 有效,但 Infowindow 无效。

我错过了什么?

function initMap() {

    // Map settings, location : Barcelona, Spain
    let map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 41.37, lng: 2.17},
        zoom: 15,
        mapTypeId: 'roadmap',
        zoomControl: true,
        mapTypeControl: false,
        scaleControl: true,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: true
    });

    // Circle distribution data : location, radius, data
    let distribution = {
        target_garden: {
            center: {lat: 41.371400, lng: 2.171942},
            population: 1,
            data: `<div>Text 01</div>`
        },
        target_wtc: {
            center: {lat: 41.373477, lng: 2.177650},
            population: 2,
            data: `<div>Text 02</div>`
        }
    };

    // Display 2 red circles on map
    let target;
    for (target in distribution) {

        let circle = new google.maps.Circle({

            // colors
            strokeColor: '#000',
            strokeOpacity: .2,
            strokeWeight: 3,
            fillColor: '#f00',
            fillOpacity: 0.5,

            // position
            map: map,
            center: distribution[target].center,
            radius: Math.sqrt(distribution[target].population) * 100,

            // settings
            draggable: false,
            editable: false,
            clickable: true

        });

        let infowindow = new google.maps.InfoWindow({
            content: distribution[target].data
        });

        // Event : on click a circle open infowindow
        circle.addListener('click', function () {
            infowindow.open(map, circle);
            console.log('on');
        });

    }

}

我希望单击红色圆圈可以打开一个信息窗口。

问题不在于循环,而是您试图将 InfoWindow 锚定到 Circle。这是来自地图 API 文档:

open([map, anchor])

Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. In the core API, the only anchor is the Marker class. However, an anchor can be any MVCObject that exposes a LatLng position property and optionally a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions).

因此,您可以以某种方式扩展 Circle 以确保它有一个位置 属性,或者您可以明确设置 InfoWindow 的位置(而不使用锚点):

circle.addListener('click', function () {
  infowindow.setPosition(circle.center) 
  infowindow.open(map);
});