D
D
Daniel2017-02-21 16:45:13
JavaScript
Daniel, 2017-02-21 16:45:13

google maps api. How to place several infoblocks on the map?

Good to everyone! There is this code:

var cityMap = new google.maps.Map(document.getElementById('cityMap'), {
    zoom: 12,
});
var infowindow = new google.maps.InfoWindow();
var services = document.getElementsByClassName('s__item');
var marker;
var geocoderCity = new google.maps.Geocoder();

for ( i=0; i < services.length; i++ ) {
    var address = $(services[i]).find('.s__item__address_at').text();
    var contentString = address;

    geocoderCity.geocode({'address': address}, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            center = results[0].geometry.location;
            cityMap.setCenter(results[0].geometry.location);

            marker = new google.maps.Marker({
                map: cityMap,
                position: center,                   
            });

            google.maps.event.addListener(marker, 'click', (function(marker) {
                return function() {
                    infowindow.setContent(contentString);
                    infowindow.open(cityMap, marker);
                }
            })(marker));
        }
    });
}

The meaning is this: there are several "s__item" blocks with addresses on the page; I get the address in a loop through the elements and get the coordinates through the geocoder; then I set markers and info windows, but in the info window on all markers only the data of the last iteration is displayed. How to do it right?
jsfiddle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2017-02-21
@Valtasaar

Well, that's right, because you have one contentString variable for the whole cycle. And when you create a marker, the last value remains in it. Wrap the creation of the marker in a separate function, then the parameter passed to it will be different for each call. https://jsfiddle.net/sxbkjxwe/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question