谷歌地图:按Id查找多边形
Google maps : Finding polygon by Id
嗨,我下面有一个多边形:
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帖子中的类似问题。希望这能让你朝着正确的方向开始。
相关文章:
- 正在全局范围中查找JavaScript函数
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在不使用jquery的情况下查找页面中的所有锚点并附加函数
- es6 相当于下划线查找位置
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何在不传递此信息的情况下查找被调用的元素
- Lodash 从值数组中查找数组中的值
- 如何使用JavaScript查找1和N之间的所有数字的总和
- 使用RegExp查找url中的字符
- 查找元素高度,包括边距
- SVG/JavaScript:尝试选择和更改多边形点
- 使用JS查找数组的平均值
- 查找最短和最长日期
- 猫鼬在特定记录中查找嵌套记录
- 使用javascript在MVC中查找网格长度时出错
- 查找多边形中多段线段的总距离
- 查找与 Google 地图多边形相交的州
- 谷歌地图:按Id查找多边形
- 在JavaScript中查找多边形的中心点