Question

I am trying to create map markers on a Google map using the Geocoder feature. I am Geocoding multiple addresses. I can successfully create the markers, but I need to also create an info window for each marker that displays various different information about the property in that location. For example, I have price information which is comma separated in an array. I have passed through the price[i] array, but I cannot manage to retrieve each price and assign it to the correct infowindow. All I get is the last price in the array being assigned to every marker. I'm trying to do it by calling the geocoder using a callback function, as I couldn't directly pass the price array into the geocoder - it came back undefined. Can anyone help?

The address array looks like this [address1,address2,address3]

The price array looks like this [500000,400000,300000]

var addresses   = address.split(','),
    prices      = price.split(',');

    var infowindow = new google.maps.InfoWindow();

    for (var i = 0; i < addresses.length; i++) {
        geocoder.geocode({'address': addresses[i]}, makeCallback(i));
    }

    function makeCallback(addressIndex) {

        var geocodeCallBack = function(results, status) {

            if (status != google.maps.GeocoderStatus.OK) {
                console.log("Geocode was not successful for the following reason: " + status);
            } else {
                var point = results[0].geometry.location;

                var i = addressIndex;
                var marker = new google.maps.Marker({
                    map: map,
                    title: "",
                    position: results[0].geometry.location
                });
                infowindow.setContent('<p>'+ prices[i] + '</p>');

                //Open the infowindow
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, this);
                });

                main.setMap(map, point, titles[i], bounds);
            }
        }

    return geocodeCallBack;
}
Was it helpful?

Solution

You're setting the content of the same infowindow for each marker, so it's showing the same one (with the last value it was assigned) no matter which marker is clicked.

Move the line var infowindow = new google.maps.InfoWindow(); to right before infowindow.setContent('<p>'+ prices[i] + '</p>'); and the correct values should appear.

Or, to have a single InfoWindow shared across all your markers (and therefore allow only one to be visible at a time):

The problem is that you're setting the content of infowindow when the markers are created rather than when they're clicked. Move the infowindow.setContent('<p>'+ prices[i] + '</p>'); to within the marker click function, right before infowindow.open(map, this);. In this case, keep the infowindow declaration where it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top