Imrana Posted August 20, 2013 Share Posted August 20, 2013 Hi all, I am working on a webapplication. I have a google map, where I add polygons from an array. I loop through that array and add the polygons to the map. I also need to add an 'click' event listener to the polygon to make it editable. This is what I am doing: var polygons = data; // array holding json objects. Each object is a polyline for(var i=0; i<polygons.length; i++) { var polygon = polygons[i]; var points = []; for(var j=0; j<polygon[1].points.length; j++) { var item = new google.maps.LatLng(polygon[1].points[j].lat, polygon[1].points[j].lng); points.push(item); } var dbpolygon=new google.maps.Polygon({ path: points, strokeColor: polygon[0].type, strokeOpacity: 0.4, strokeWeight: 2, fillColor: polygon[0].type, fillOpacity: 0.4, editable: false }); dbpolygon.setMap(map); google.maps.event.addListener(dbpolygon, 'click', function() { setSelection(dbpolygon); }); } Problem The polygons are all drawing correctly. However the problem is that when I try to click on a polygon it always selects the last index. it is like it is only clicking on the last polygon added. I think when I add a new listener it overrides the old one. How can I add a listener for each polygon added in order to alert the correct index? Thank you Quote Link to comment Share on other sites More sharing options...
Solution kicken Posted August 20, 2013 Solution Share Posted August 20, 2013 If you want to find out more about why it is only using the last item the way it is now, read through Closures on MDN, in particular the bit titled Creating closures in loops: A common mistake. In there they recommend creating a factory function to solve the issue. This would work, however in your case it is not necessary. You may use this inside your callback function to refer to the polygon that was clicked. google.maps.event.addListener(dbpolygon, 'click', function() { setSelection(this); }); Quote Link to comment Share on other sites More sharing options...
Imrana Posted August 21, 2013 Author Share Posted August 21, 2013 Hi Kicken, Thank you so much for helping me with this. using the 'this' keyword has resolved my problem. I will through the link you have suggested and have a look at the factory pattern. Thank you again Imran Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.