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

Hidden markers appear after zoom - API Google Maps V3


I have markers in a map and i use this to remove them..

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

But when i change the zoom of the map, all markers appearing again.

Does anyone know what is it?

var map;
var idInfoBoxOpen;
var infoBox = [];
var markers = [];

function initialize() 
{   
    var latlng = new google.maps.LatLng(-18.8800397, -47.05878999999999);   
    var options = {
        zoom: 5,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapa"), options);
}
initialize();

function openInfoBox(id, marker) {
    if (typeof(idInfoBoxOpen) == 'number' && typeof(infoBox[idInfoBoxOpen]) == 'object') 
    {
        infoBox[idInfoBoxOpen].close();
    }
    infoBox[id].open(map, marker);
    idInfoBoxOpen = id;
}

function loadPoints()
{
    $.getJSON('assets/json/pontos.json', function(points) 
    {
        var latlngbounds = new google.maps.LatLngBounds();
        $.each(points, function(index, point) 
        {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(point.Latitude, point.Longitude),
                title: "Desc",
                icon: 'assets/img/point.png',
            });

            var myOptions = {
                content: "<p>" + point.Descricao + "</p>",
                pixelOffset: new google.maps.Size(-150, 0)
            };

            infoBox[point.Id] = new InfoBox(myOptions);
            infoBox[point.Id].marker = marker;
            infoBox[point.Id].listener = google.maps.event.addListener(marker, 'click', function (e) {
                openInfoBox(point.Id, marker);
        });
            markers.push(marker);
            latlngbounds.extend(marker.position);   
        });
        var markerCluster = new MarkerClusterer(map, markers);
        map.fitBounds(latlngbounds);

    });

}

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

function reset(value)
{
    clearMarkers();
}

loadPoints();

Solution

  • You need to remove the markers from the markerClusterer if you don't want them to come back when you change the zoom.

    markerCluster.clearMarkers();
    

    (and make the markerCluster variable global, it is currently local to the AJAX callback function)