Search code examples
javascriptgoogle-mapsmapspolygongoogle-maps-engine

Google maps : Finding polygon by Id


Hi I have a polygon below :

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);

I attached an id property to it so i can refer to it later on, the problem is. How do I find that same polygon and trigger an event? like a change color or something?

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

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

Many thanks!


Solution

  • From what I understand, you want to trigger an event after finding the polygon with a specific id.

    Now, one thing you can do is just add an event listener to the polygon and refer to the polygon using the this context. You can then trigger the change of colour accordingly (for example):

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

    In your case however, if you don't want to trigger the color change on a specific even listener that can be added to the polygon. You could simply store the polygons in a polygon array and loop through them in your specific function that changes the colors. So you could try something like this (untested):

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

    You might also want to check some other SO Posts on a similar issue. Hope this gets you started in the right direction.