Search code examples
javascriptgoogle-mapsgoogle-maps-api-3markerclusterer

markerCluster not showing points


I am trying to clustering some location on google map. I have tryied to merge the code from from this question and the code from markercluster examples. But can't fix it. This is my code:

<div id="map_canvas" style="width: 98%; height: 500px;border:2px solid #ccc;float:left"></div>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>     
    <script>
function initialize() {
var elevator;
var myOptions = {
    zoom: 2,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: 'terrain'
    };
var map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Argentina, Buenos Aires', 'Argentina, Cordoba, Cordoba Capital','Argentina, Cordoba, Rio Tercero'];
var markers = [];
for (var x = 0; x < addresses.length; x++) {
    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
        var p = data.results[0].geometry.location
        var latlng = new google.maps.LatLng(p.lat, p.lng);
        var marker = new google.maps.Marker({position: latlng });
        markers.push(marker);
    });
    }
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
    </script>   

It is not a problem of jquery, because the example works very well if I don't try to use markerCluster. So I am doing something wrong with array passing.


Solution

  • $.getJSON runs asynchronously, markers will not be populated yet when you use it as argument for MarkerClusterer.

    Use

    markerCluster.addMarker(marker);
    

    instead of

    markers.push(marker);