3

So i have several markers appearing from an array, but i'm having a lot of difficulty setting the content of the InfoWindows that appear

I put the titles in which works great, but when I try to set the content, it doesn't set the content, but still shows the title.

What am I doing wrong?

for (index = 0; index < data.length; ++index) {
    locationName = data[index].LocationName;
    locationID = data[index].LocationID;
    locationX = data[index].XCord;
    locationY = data[index].YCord;
    var infoContent = '<div><h3>' + data[index].LocationName + '</h3></div><div>' + data[index].LocationID +  '</div>';
    var mapLocation = new google.maps.LatLng(locationX,locationY);
    var marker = new google.maps.Marker({ // Set the marker
        position: mapLocation, // Position marker to coordinates
        icon: image, //use our image as the marker
        map: map, // assign the marker to our map variable
        title: data[index].LocationName,
        content: infoContent
        //draggable:true //Have a guess what this does
    });

    // Allow each marker to have an info window    
    google.maps.event.addListener(marker, 'click', (function (marker, index) {
        return function () {
            infoWindow.setContent(infoContent);
            infoWindow.setContent(this.title);
            infoWindow.open(map, this);
        }
    })(marker, index));

    var infoWindow = new google.maps.InfoWindow({ 
        content: infoContent 
    }), marker, index;
}
kingtreelo
  • 251
  • 3
  • 15

1 Answers1

1

You are calling setContent twice:

infoWindow.setContent(infoContent);
infoWindow.setContent(this.title);

I guess the last one should be removed.

Edit:

To get the correct infoWindow content, try moving the creation of the eventListener to a function:

// Allow each marker to have an info window    
updateInfoWindowOnMarkerClick(marker, infoContent); 

//Somewhere after the loop
function updateInfoWindowOnMarkerClick(marker, infoContent){
    google.maps.event.addListener(marker, "click", function () {
        infoWindow.setContent(infoContent);
        infoWindow.open(map, this);
    });      
}          

Have a look at JavaScript closure inside loops – simple practical example for more information about function scope.

Community
  • 1
  • 1
gusjap
  • 2,397
  • 5
  • 24
  • 38