简体   繁体   中英

Google Maps ClusterManager on API V3 not working on reload / initial load

I am trying to use the Google Maps V3 API ClusterManager from http://cm.qfox.nl/ to cluster together markers on a map, but I'm hitting the same error in my code as in the original web site - an error when the page is loaded the first time, or reloaded:

Uncaught TypeError: Cannot call method 'fromLatLngToPoint' of undefined ClusterManager_v3.js:586
ClusterManager.latlngToPoint ClusterManager_v3.js:586
ClusterManager._getMarkerBounds ClusterManager_v3.js:645
ClusterManager._cacheMarkerIcon ClusterManager_v3.js:580
ClusterManager.update ClusterManager_v3.js:345
(anonymous function) ClusterManager_v3.js:91

It works fine after the initial load, so I'm fairly sure it's because of a timing issue - eg, the map or marker isn't initialized before it being used. Unfortunately, I can't figure out a way to wait for everything to initialize because Javascript isn't my first language. Any help or pointers would be most welcome. The source from the web site is the code I'm using almost exactly.

UPDATE:

If found that changing the line:

cm._requestUpdate(50);

to

cm._requestUpdate(250);

Prevented the error. Changing it to 150 resulted in the error occurring 3/10 times. I'm not entirely sure this is a fix, but it maybe so I'm leaving this posted just in case anyone else has a better solution or wants to know mine.

For using Projection methods, it must be initialized. Map will trigger "projection_changed" event, when Projection will be created.Only after that you can use map.getProjection() . So my suggestion is, to add "projection_changed" event's listener, and initialize ClusterManager when it is called:

google.maps.event.addListenerOnce(map, 'projection_changed', function(){
     var cm = window.cm = new ClusterManager(
        map,
        {
            objClusterIcon: new google.maps.MarkerImage('markers/cluster.png', false, false, false, new google.maps.Size(20,20)),
            objClusterImageSize: new google.maps.Size(20,20)
        }
    );

    // now json contains a list of marker positions. lets add them.
    for (var i = 0; i < json.length; ++i) {

       .....
    }
    cm._requestUpdate(50);
});

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