为 Google 地图上的多个形状创建 addListener 单击事件

Use*_*Mat 3 events overlay google-maps-api-3

看看这段代码:这会在地图上的同一位置创建四个圆圈,它也为每个圆圈创建了 addListener 单击事件,但我只能单击最后一个。我想以一种可以点击所有这些来为每个人设置 setEditable(true) 的方式来修复它。

<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>

<script>
var selectedShape;

function clearSelection()
{
    if(selectedShape)
    {
        selectedShape.setEditable(false);
        selectedShape = null;
    }
}

function setSelection(shape)
{
    clearSelection();
    selectedShape = shape;
    shape.setEditable(true);    
}
</script>


<script>
var amsterdam=new google.maps.LatLng(52.395715,4.888916);
function initialize()
{
    var mapProp = {center:amsterdam, zoom:7, mapTypeId:google.maps.MapTypeId.ROADMAP};
    var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

    var myArray = [];
    var myCity;

    for(var i = 0; i < 4; i++)
    {
        myCity = new google.maps.Circle({
            center:amsterdam,
            radius:20000,
            strokeColor:"#0000FF",
            strokeOpacity:0.8,
            strokeWeight:2,
            fillColor:"#0000FF",
            fillOpacity:0.4
          });


    myArray.push(myCity);

    google.maps.event.addListener(myCity, 'click', function() {setSelection(myCity)});
    myArray[i].setMap(map);

  }

}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

dav*_*rad 5

使用this代替myCity

google.maps.event.addListener(myCity, 'click', function() {
   setSelection(this)
});
Run Code Online (Sandbox Code Playgroud)

UsingsetSelection(myCity)将引用最后创建的 myCity。