Search code examples
javascriptgoogle-mapsclickinfowindow

Google Map InfoWindow not opening on click in loop


I cannot get the info window on Google Map API to open on click within loop, however all info windows show the outside click event.

var map;
function initMap() {
    var mapProp = {
       center: new google.maps.LatLng(-22, 133),
       zoom: 4,
       mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map'), mapProp);
}
var request = new XMLHttpRequest();
request.open('GET', 'https://...', true);
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);
        appendData(data.data);
        console.log(data, "Data received");
    } else {
        // We reached our target server, but it returned an error
    }
};
request.onerror = function() {
    // There was a connection error of some sort
};
request.send();
function appendData (data) {
    var markers = [];
    for (var i = 0; i < data.length; i++) {
        var pos = new google.maps.LatLng(data[i].Latitude, data[i].Longitude);
        markers[i] = new google.maps.Marker({
            position: pos,
            map: map,
            icon: '//...icon.png'
        });
        var infowindow = new google.maps.InfoWindow({
            content: data[i].Name
        });
        //infowindow.open(map, markers[i]); - this shows all infowindows..
        //Something wrong with this click event
        google.maps.event.addListener(markers[i], 'click', function() {
            infowindow.open(map, markers[i]);
        });
    }
};

Solution

  • All ok worked it out. Added description and id to markers and setContent to click event triggering this

    markers[i] = new google.maps.Marker({
                    position: pos,
                    map: map,
                    icon: 'icon.png',
                    description:"<div style='text-transform:uppercase;'><h6 style='color:red'>" + data[i].Name + "</h6>" + data[i].Description + "</div>",
                    id: i
    });
    google.maps.event.addListener(markers[i], 'click', function () {
    
                    infowindow.setContent(markers[this.id].description);
                    infowindow.open(map, this);
    });