I have a snippet of code that creates an array clusterUniqueMarkers that stores all the unique objects in the array clusterMarkers.
Problem: With the help of console.log(clusterUniqueMarkers.length); I can see that the size of that array blows up! When the code is executed, the browser CPU & memory usage shoots up and crashes. What could have caused the problem?
JS Code
// MarkerClusterer click handler
google.maps.event.addListenerOnce(mc, "clusterclick", function (cluster) {
// Find number of unique LatLng in clusters
var clusterMarkers = mc.getMarkers();
var clusterUniqueMarkers = [];
for(var j = 0; j < clusterMarkers.length; j++) {
if(clusterUniqueMarkers.length == 0){
// Adding first unique marker
clusterUniqueMarker = new Object();
clusterUniqueMarker.lat = mc.getMarkers()[j].position.lat();
clusterUniqueMarker.lng = mc.getMarkers()[j].position.lng();
clusterUniqueMarkers.push(clusterUniqueMarker);
} else {
// At least 1 unique marker
var clusterUniqueMarkersLength = clusterUniqueMarkers.length; // prevent infinite loop when clusterUniqueMarkers.length keeps increasing
console.log(clusterUniqueMarkers.length);
console.log(clusterUniqueMarkersLength);
console.log('j: ' + j);
for(var k = 0; k < clusterUniqueMarkersLength; k++) {
// If marker is unique
if(clusterUniqueMarkers[k].lat != mc.getMarkers()[j].position.lat() && clusterUniqueMarkers[k].lng != mc.getMarkers()[j].position.lat()) {
clusterUniqueMarker = new Object();
clusterUniqueMarker.lat = mc.getMarkers()[j].position.lat();
clusterUniqueMarker.lng = mc.getMarkers()[j].position.lng();
clusterUniqueMarkers.push(clusterUniqueMarker);
}
}
}
}
console.log(clusterMarkers);
console.log(clusterUniqueMarkers);
});
Your logic is wrong. You’re iterating through all the elements in
clusterMarkers, and doing this:If the unique list is empty, add the current element as a unique one.
If the unique list is not empty, iterate through the unique list, and if the current element doesn’t match the current unique element, add it as a unique one. What you want to do is say “if the current element doesn’t equal any of the unique ones, add it as a unique one”, which this code will achieve: