Геокодер асинхронный. Массив маркеров пуст, когда вы добавляете его в markerClusterer.
Создайте MarkerClusterer перед l oop, затем переместите markerClusterer.addMarker(marker);
внутри процедуры обратного вызова геокодера.
function codeAddress() {
var markers = [];
var address = ['Reston, VA']
address.push('Herndon, VA');
address.push('San Francisco, CA')
address.push('San Jose, CA')
const markerClusterer = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
maxZoom: 5
});
for (i = 0; i < address.length; i++) {
geocoder.geocode({
'address': address[i]
}, function(results, status) {
if (status == 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markers.push(marker);
markerClusterer.addMarker(marker);
} else {
alert('Geocoding did not work' + status);
}
});
}
}
доказательство концепции скрипта
фрагмент кода:
var map;
var geocoder;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
}
});
geocoder = new google.maps.Geocoder();
codeAddress();
}
function codeAddress() {
var markers = [];
var address = ['Reston, VA']
address.push('Herndon, VA');
address.push('San Francisco, CA')
address.push('San Jose, CA')
const markerClusterer = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
maxZoom: 5
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < address.length; i++) {
geocoder.geocode({
'address': address[i]
}, function(results, status) {
if (status == 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markers.push(marker);
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
markerClusterer.addMarker(marker);
} else {
alert('Geocoding did not work' + status);
}
});
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>