Problems to delete a "circle" object that is on google-maps

1

I'm having trouble deleting circle-like objects (API google-maps) being shown on my map.

I have a function that receives JSON data and creates a global array ( arrayElements ) containing objects ( element ) that have: JSON information and an < circle ) circle the google maps API. When I do a search (I get a new JSON), I access arrayElements , and for each element , I access the circle and run the function circle.setMap (null) , however, the problem is that some circles erase while others remain. I have debugged, but I could not identify the error.

var arrayElementos = [];

function setMapElements(mJsonData) {


    if(arrayElementos.length==0){

        var elementOptions = {
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 1,
            fillColor: "#FF0000",
            fillOpacity: 0.35,
            map: map,
            center: {},
            radius: Math.sqrt(1) * 50
        };

        var elemento = {

            idade:{},
            genero:{},
            circulo:{}
        };

        $.each(mJsonData, function(id,data){

            elementOptions.center = new google.maps.LatLng(data.latitude,data.longitude);

            elemento.genero = data.sexo;
            elemento.idade = data.idade;
            elemento.circulo = new google.maps.Circle(elementOptions);

            mapElements.push(elemento);
        });

    }else{

        $.each(arrayElementos, function(id,elemento){

            elemento.circulo.setMap(null);

        });

        arrayElementos = [];

        setMapElements(mJsonData);
    }

};
    
asked by anonymous 25.03.2015 / 01:51

1 answer

2

You are creating a single object elemento and overwriting its fields at each iteration of the loop.

 var elemento = {
    idade:{},
    genero:{},
    circulo:{}
};

$.each(mJsonData, function(id,data){

    elementOptions.center = new google.maps.LatLng(data.latitude,data.longitude);

    elemento.genero = data.sexo;
    elemento.idade = data.idade;
    elemento.circulo = new google.maps.Circle(elementOptions);

    mapElements.push(elemento);
});

Instead of reusing a single element, create a new element with each step:

$.each(mJsonData, function(id,data){

    elementOptions.center = new google.maps.LatLng(data.latitude,data.longitude);

    mapElements.push({
        genero : data.sexo,
        idade : data.idade,
        circulo : new google.maps.Circle(elementOptions)
    });
});

A simpler program that illustrates your bug is this one:

var obj = {}
var lista = [];
for(var i=0; i<10; i++){
    obj.x = i;
    lista[i] = obj;
}
obj.y = 17;

If you print the list contents at the end, you will see that all fields point to the same object.

    
25.03.2015 / 02:13