Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a reference to the polygon clicked? (google maps api v3)

I've set up some polygons, drew them on the map just fine. I also managed to fire console.log when they were clicked. However, how would I go on about figuring out which polygon was actually clicked?

As you can see in my sample code here I store each object within the collection "lots", however - clicking them only gives me the lat-long of the click. I figured I might need to loop through my polygons and check if the point was clicked is intersecting them and thus figure out which polygon it is... is there an easier solution?

var lot = new google.maps.Polygon({
    paths: me.area,
    strokeColor: 'black',
    strokeOpacity: 0.35,
    strokeWeight: 1,
    fillColor: fillcol,
    fillOpacity: 0.35
});

lot.setMap(map);
var obj = {
    'id':me.id,
    'rented':me.rented,
    'area':lot
};

google.maps.event.addListener(lot, 'click', function(event) {
    console.log(event);
});

lots.push(lot);
like image 398
Bisa Avatar asked Sep 28 '11 10:09

Bisa


1 Answers

Why don't assign to each polygon some id property when you create them and later just use this.myID? Truly speaking, you can hang all information you need on that polygon object.

var lot = new google.maps.Polygon({
        paths: me.area,
        strokeColor: 'black',
        strokeOpacity: 0.35,
        strokeWeight: 1,
        fillColor: fillcol,
        fillOpacity: 0.35
    });

    lot.setMap(map);

    var obj = {
        'id':me.id,
        'rented':me.rented,
        'area':lot
    };
    lot.objInfo = obj;

    google.maps.event.addListener(lot, 'click', function(event) {
        console.log(this.objInfo);
    });

    lots.push(lot);

It would be more effective than path comparison in a loop, or am i missing something? :)

like image 82
dmitry Avatar answered Oct 26 '22 12:10

dmitry