4

嗨,我在下面有一个多边形:

var polygon = new google.maps.Polygon({
              paths: coords,
              id : 123,
              strokeColor: '#FF0000',
              strokeOpacity: 0.8,
              strokeWeight: 1,
              fillColor: '#FF0000',
              fillOpacity: 0.35
            });

polygon.setMap(globalMap);

我给它附加了一个id属性,所以我以后可以参考它,问题是。如何找到相同的多边形并触发事件?比如改变颜色之类的?

function changePolygonColor(){
//refer to the polygon with id 123 (this is my question)

//change its color
polygon.fillColor = '#00FF00';
}

非常感谢!

4

1 回答 1

5

据我了解,您想在找到具有特定id.

现在,您可以做的一件事就是将事件侦听器添加到并使用上下文polygon引用多边形。this然后,您可以相应地触发颜色变化(例如):

google.maps.event.addListener(polygon, 'click', function (event) {
  alert(this.id);
  //Once you have the id here, you can trigger the color change
});  

但是,在您的情况下,如果您不想触发可以添加到polygon. 您可以简单地将多边形存储在多边形数组中,并在更改颜色的特定函数中循环遍历它们。所以你可以尝试这样的事情(未经测试):

var polygonArray = []; //Have a global array of polygon elements
polygonArray.push(polygon); //Push your polygons as you create them into this polygon array

...

function changePolygonColor(){
 //refer to the polygon with id 123 (this is my question)
 //Loop through the polygon array
  for (var i = 0; i < polygonArray.length; i++) {
   if(polygonArray[i].id == 123) //Or whatever that you require
     {
       //change its color 
       polygon[i].fillColor = '#00FF00';
     }
  }
}

您可能还想查看有关类似问题的其他一些 SO 帖子。希望这能让你朝着正确的方向开始。

于 2014-10-13T03:46:31.293 回答