Google地图:按ID查找多边形

时间:2014-10-13 03:14:45

标签: javascript google-maps maps polygon google-maps-engine

嗨我下面有一个多边形:

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

非常感谢!

1 个答案:

答案 0 :(得分:4)

根据我的理解,您希望在找到具有特定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';
     }
  }
}

您可能还想在类似问题上查看一些other SO Posts。希望这能让你开始朝着正确的方向前进。