在Google地图上为多个形状创建addListener点击事件

时间:2013-10-30 09:38:01

标签: events google-maps-api-3 overlay

看看这段代码: 这会在地图上创建四个相同位置的圆圈,并为每个圆圈创建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>

1 个答案:

答案 0 :(得分:3)

使用this代替myCity

google.maps.event.addListener(myCity, 'click', function() {
   setSelection(this)
});

使用setSelection(myCity)将参考最后创建的myCity。