0

so im doing, some magic with polygons in google maps. the thing is that im watching events on every polygon path (to detect changes on the polygon nodes with the 'set_at' and 'insert_at' events) , I loop on a polygons array and create this event (among others)

coffeescript

google.maps.event.addListener(polygon.getPath(), 'insert_at', (index) ->

every polygon has an id. but from this scope i can not access the parent element, and i need to save changes from the changed polygon... is there any way of geting the id of the parent polygon from this event listener?

  • For Javascript, you can create an `indexID` when you are creating a new polygon object, in your event listener, you can just get the `indexID` for each polygon, Javascript answer: http://stackoverflow.com/a/15209277/4195406 – ztan Oct 05 '15 at 18:30
  • I solved the problem by wrapping all node events on a polygon event. I already have a index property on each polygon but you cannot access polygon properties on node events. the way is to wrap the polygon.getPath() envents on a onClick event binded to the current polygon in the loop. As you can see, the event its binded to the .getPath() method cause the scope of the event doesent have the polygon and its properties. – Mijail Cohen Oct 05 '15 at 18:49

1 Answers1

0

I'm assuming that polygonsArray is your array of polygons, so your loop should be like this ...

    for (var u=0; u < polygonsArray.length; u++) {
        var polygonOptions = {
            fillColor: 'blue',
            strokeWeight: 1,
            name: "Any Name"
        };

        //  1\ Creat polygon
        var polygon = new google.maps.Polygon(polygonOptions);
        //  2\ Set polygon path
        var pathArr = polygonsArray['path'];
        polygon.setPaths(pathArr);

        //xxxxxxxxxxxxxxxxxxxxx MAGIC HERE xxxxxxxxxxxxxxxxxxxxxxxxxx
        //  2.5\ Give polygon index as a path object new attribute
        var path = polygon.getPath();
        path["parentIndex"] = u;
        //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        //  3\ Add polygon to map
        polygon.setMap(map);

        //  4\ Add events to polygon
        //Listen to any modification occures to the path
         google.maps.event.addListener(polygon.getPath(), 'set_at', function() {
              console.log(this["parentIndex"]);
        });

        //Listen to new point inserted to the path
         google.maps.event.addListener(polygon.getPath(), 'insert_at', function() {
             console.log(this["parentIndex"]);
        });            



    }//End of loop
Husam
  • 8,149
  • 3
  • 38
  • 45