简体   繁体   中英

Multiple Markers on Google Map: only last marker is shown

I am having a problem with displaying multiple markers on my map. The code starts by looping through an array, and then reverse geocoding the lat, lon values before displaying a marker and setting the content of the infoWindow to the returned address.

My codes are below.

for(var i=0; i < useNowArray.length; i++) {
        // plot useNow on map
        latlng = new google.maps.LatLng(useNowArray[i]['lat'], useNowArray[i]['lon']);
        console.log(useNowArray[i]['lat'] + useNowArray[i]['lon']);
        geocoder.geocode({'latLng': latlng}, function(results, status) 
        {
            if (status == google.maps.GeocoderStatus.OK) 
            {
                if (results[0]) 
                {
                    marker = new google.maps.Marker({
                        position: latlng,
                        map: map,
                        icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png',
                        title: results[0].formatted_address
                    });
                    content = results[0].formatted_address;
                    console.log(content);

                    google.maps.event.addListener(marker, 'click', (function(marker, i) {
                        return function() {
                            infowindow.setContent(content);
                            infowindow.open(map, this);
                        }
                    })(marker, i));
                }
            } else {
                alert("Geocoder failed due to: " + status);
            }
        }); // end geocode function
    }  
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 

The issue is that only my last marker is shown.

What am i missing? :(

many thanks.

Your marker variable is global, geocoding is asynchronous. The loop executes, firing off useNowArray.length requests, each one updates the global marker with the resulting position. When the loop is done, the marker is left at the last location in the loop. Similar questions with solutions to the issue:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM