5

I have a lot of polygons created dynamically on a Google Maps, using API v3. I don't have a global array of them. I assign event for each after creation, because I need to track the changes made to them by the user. Everything work fine, except one thing.

path = polygon.getPath(); //Note, that polygon isn't a global variable
//DragEnd
google.maps.event.addListener(polygon, "dragend", function(){
    SavePolygonToDb(this);
});
//Edited
google.maps.event.addListener(path, "set_at", function() {
    //Now 'this' is the path array, not the polygon 
    SavePolygonToDb(????);
});

Somehow I need to get the polygon object, which the path belongs to, but I can't find a way for it. The only solution, that I came up with, that I need to store all the polygons and their paths in an array, then if something changes, I loop through the array and compare the path values to the actual ones. If some LatLng coordinate differs, then the polygon changed. Save the new values to tha backend array, and go on. But I think, there must be some other (easier) solution to do this.

Fenistil
  • 3,734
  • 1
  • 27
  • 31

1 Answers1

9

Meanwhile I came up with a simple solution. Define a global array for the polygons:

var polygonArray = [];

When creating the polygons, push them into that array:

polygonArray.push(polygon);

And add an event listener like this:

google.maps.event.addListener(path, "set_at", function(){
    for (i in polygonArray) {
        if (polygonArray[i].getPath() == this) {
            alert('Got it'); //polygonArray[i]
        }
    }
});
Fenistil
  • 3,734
  • 1
  • 27
  • 31