0

I'm trying to create a group of markers with info box attached. However, no matter which marker I click, it always opens the info box of the last detailmarker. Anyone know why? Please help.

var stepDisplay = new google.maps.InfoWindow();
function AddDetailMarker(map, itinerary) {
    var markers = [];
    for (var i = 1; i < itinerary.Legs.length; i++) {
        var position = new google.maps.LatLng(itinerary.Legs[i].BusStop.Latitude, itinerary.Legs[i].BusStop.Longitude);
        var title = itinerary.Legs[i].BusStop.Code + ": " + itinerary.Legs[i].BusStop.Location + " " + itinerary.Legs[i].BusStop.Street + ", Quận " + itinerary.Legs[i].BusStop.Ward;
        var detailmarker = new google.maps.Marker({
            position: position,
            map: map,
            title: title,
            icon: "/Content/img/customized_marker/" + "blue" + "/" + "bus-stop2" + ".png"
        });
        google.maps.event.addListener(detailmarker, 'click', function () {
            stepDisplay.setContent(title);
            stepDisplay.open(map, detailmarker);
        });
        markers[i-1] = detailmarker;
    }
}

Edit: possible dublicate of Google maps infowindow showing on wrong marker. I've tried all the solutions I found here and none works.

Community
  • 1
  • 1
vCube
  • 171
  • 2
  • 12

1 Answers1

0

Yes, this is exactly the same problem as the other one you linked to, and the solution for your code is the same - put the code to create each marker into a function, and call that function in your loop:

var stepDisplay = new google.maps.InfoWindow();
function AddDetailMarker(map, itinerary) {
    for (var i = 1; i < itinerary.Legs.length; i++) {
        addLegMarker( map, itinerary.Legs[i] );
    }
}

function addLegMarker( map, leg ) {
    var position = new google.maps.LatLng(leg.BusStop.Latitude, leg.BusStop.Longitude);
    var title = leg.BusStop.Code + ": " + leg.BusStop.Location + " " + leg.BusStop.Street + ", Quận " + leg.BusStop.Ward;
    var detailmarker = new google.maps.Marker({
        position: position,
        map: map,
        title: title,
        icon: "/Content/img/customized_marker/" + "blue" + "/" + "bus-stop2" + ".png"
    });
    google.maps.event.addListener(detailmarker, 'click', function () {
        stepDisplay.setContent(title);
        stepDisplay.open(map, detailmarker);
    });
}

Do you see why that fixes it? The title and detailmarker are now specific to each invocation of addLegMarker(). In the original code, there was only a single copy of each of these variables, shared among all markers.

Michael Geary
  • 28,450
  • 9
  • 65
  • 75