Jump to content

Google Maps - Add click listener to each polygon


Imrana

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.