谷歌地图:按Id查找多边形

Google maps : Finding polygon by Id

本文关键字:查找 多边形 Id 谷歌地图      更新时间:2023-09-26

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

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

非常感谢!

据我所知,您希望在找到具有特定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帖子中的类似问题。希望这能让你朝着正确的方向开始。