user1040259
user1040259

Reputation: 6509

Google Maps clear placed MarkerClusters on new search

I'm having trouble getting my map to clear the clusters on a new search. Any ideas?

function clearLocations() {
    //infoWindow.close();
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers.length = 0;

    // clear #side_bar bottom text
    document.getElementById("side_bar").innerHTML = "";
    // clear .alertBox text
    $('.alertBox').html('');
}


function searchLocationsNear(center) {
    clearLocations();

    var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng();
    downloadUrl(searchUrl, function (data) {
        var xml = parseXml(data);
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        if (markerNodes.length > 0) {

            var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < markerNodes.length; i++) {
                var name = markerNodes[i].getAttribute("name");
                var address = markerNodes[i].getAttribute("address");
                var distance = parseFloat(markerNodes[i].getAttribute("distance"));
                var category = markerNodes[i].getAttribute("category");
                var latlng = new google.maps.LatLng(
                    parseFloat(markerNodes[i].getAttribute("lat")),
                    parseFloat(markerNodes[i].getAttribute("lng")));

                // createOption(name, distance, i);
                createMarker(latlng, name, address, category);
                bounds.extend(latlng);
            }
            map.fitBounds(bounds);
            var markerclusterer = new MarkerClusterer(map, markers);
          // markerclusterer.setMap(null);
            makeSidebar(); 

        } else {
            $('.alertBox').html('Sorry, there are no jobs that are close to your location.');
        }
   });
}

Upvotes: 0

Views: 285

Answers (1)

Preview
Preview

Reputation: 35806

You should try this :

if (markers) {
    for (i in markers) {
        markers[i].setMap(null);
    }
    markers = [];
    markerclusterer.clearMarkers()
}

According to the docs the clusterer can be clear with clearMarkers() method.

UPDATE

Call clear only when we have already create the MarkerClusterer.

if(markerclusterer)
{
    clearLocations();
}

Upvotes: 1

Related Questions