【问题标题】:Google maps : Finding polygon by Id谷歌地图:按 ID 查找多边形
【发布时间】:2014-12-07 13:42:30
【问题描述】:

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

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

非常感谢!

【问题讨论】:

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


    【解决方案1】:

    据我了解,您希望在找到具有特定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 关于类似问题。希望这能让您朝着正确的方向开始。

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 2011-12-03
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 2012-09-12
      相关资源
      最近更新 更多