问题描述:

Simply put, I am trying to dynamically create a marker and corresponding label for each property of in the loop. The label will contain the time-stamp.

However, I am fairly stuck on figuring out how to get the on-click function to remain bound to it's respective marker. The infowindow variable as well.

I have tried using a counter and creating an array of variables to reference each function. I have also tried eval and creating new variables within the global window

window["foo" + counter]

unsuccessfully. With all variations of this that I have tried the code has broken or resulted in all triggers/infowindows being bound to the same property.

Any help or direction would be greatly appreciated. I think I am just missing some depth on understanding variable/object scope. This base code results in all markers appearing and the final label (since the previous ones are overwritten) as depicted below.

variables:

prop = string representing long,lat coordinates

obj[prop] = An ISOformat timestamp

Rest of the code taken from marker Labels Google Maps API

 for (var prop in obj) {

// skip loop if the property is from prototype

if(!obj.hasOwnProperty(prop)) continue;

var templocs = prop.split(",").map(Number);

console.log(templocs[0]);

var temppos = new google.maps.LatLng(templocs[0], templocs[1]);

var mark = new google.maps.Marker({

position:temppos,

map: map,

animation:google.maps.Animation.BOUNCE,

});

var infowindow = new google.maps.InfoWindow({

content: "date taken: " + obj[prop],

maxWidth: 200

});

mark.addListener('click', function() {

infowindow.open(map, mark);

});

}

网友答案:
    var cnt = 0;
    var infowindow = [];
    var mark = [];
    var bounds = new google.maps.LatLngBounds();

    for (var prop in obj) {
        // skip loop if the property is from prototype
        if(!obj.hasOwnProperty(prop)) continue;

        var templocs = prop.split(",").map(Number);
        console.log(templocs[0]);
        var temppos = new google.maps.LatLng(templocs[0], templocs[1]);

        infowindow[cnt] = new google.maps.InfoWindow({
            content: "date taken: " + obj[prop],
            maxWidth: 200
        });         


        mark[cnt] = new google.maps.Marker({
            position: temppos,
            map: map,
            animation:google.maps.Animation.BOUNCE,

        });


/*      mark[cnt].addListener('click', function() {
            infowindow[cnt].open(map, mark);
        });     */  

        google.maps.event.addListener(mark[cnt], 'click', (function(markerrr, cnt) {
          return function() {
            infowindow[cnt].open(map, mark[cnt]);
          }
        })(mark[cnt], cnt));
        bounds.extend(mark[cnt].getPosition());

        cnt++;
    }

Fixed. This post is a duplicate of this one

Issue had to do with closure.

相关阅读:
Top