Teresa Alves
Teresa Alves

Reputation: 523

Variable is storing two values in javascript

I have a map with a few markers. Each marker has a infowindow with 3 buttons. Each button, when clicked changes the icon of the marker. However when I open the infowindow of one marker and don't click on any button,and go to another marker and click in one of the buttons, both markers change icons, instead of changing only the last one cliked. Here is my code:

  //Get de todas as ignições presentes na base de dados
$.get("/api/IgnicoesAPI", function (data) {


    //alert(aceite)
    console.log(data);
 
    $.each(data, function (i, item) {

        //identificação do tipo de marcador que deve aparecer de acordo com o estado da ignição
        var ignicao;

       // MORE CODE

        var id = item.id;
     
        //colocar um marcador no mapa de acordo com a latitude e longitude fornecidas
        var marker = new L.marker([item.latitude, item.longitude], { icon: ignicao })

            .on("click", function onClick(e) {
              
                //assim que um marcador for clicado é mostrado o popup das ignições
                modal.style.display = "block";

                //indicação do marcador que foi clicado
                clickedmarker = e.target;
                console.log(clickedmarker);


                //vai buscar toda a informação correspondente ao id fornecido
                getData(id);

                //Actividade dos botões presentes no popup das ignições
                $(document).on("click", "#aceite", function () {
                    //se o estado for aceite, o botão respetivo estará desativado
                    if (item.estado == aceite) {
                        document.getElementById("aceite").disabled = true;
                        document.getElementById("recusado").disabled = false;
                        document.getElementById("concluido").disabled = false;

                    }
                    //se for clicado passará ao icon correspondente
                    else {
                        clickedmarker.setIcon(accepted);
                       //fecha o modal das avaliação da ignição
                        modal.style.display = "none";
                        //atualiza a base de dados com o novo estado
                        atualizaBD(id, Estado.aceite, item.latitude, item.longitude);
                    }


                });

                 $(document).on("click", "#concluido", function () {
                     //se o estado for concluido, o botão respetivo estará desativado
                     if (item.estado == concluido) {

                        document.getElementById("concluido").disabled = true;
                        document.getElementById("aceite").disabled = false;
                        document.getElementById("recusado").disabled = false;
                    }
                    //se for clicado passará ao icon correspondente
                     else {
                         
                         clickedmarker.setIcon(conclued);
                        //fecha o modal das avaliação da ignição
                         modal.style.display = "none";
                         
                         //atualiza a base de dados com o novo estado
                         atualizaBD(id, Estado.concluido, item.latitude, item.longitude);

                        
                        


                    }

                });
                
                $(document).on("click", "#recusado", function () {
                    //se o estado for recusado, o marcador será removido do mapa
                    //clickedmarker.removeFrom(map);
                   
                   
                    //map.removeLayer(clickedmarker)
                    
                    map.removeLayer(marker)
             

                    modal.style.display = "none";
                    //atualiza a base de dados com o novo estado
                    atualizaBD(id, Estado.recusado, item.latitude, item.longitude);

                   
                   
                    
                    
                });
        
            }).addTo(map);
       
        //adiciona marador ao mapa
        $('#json map').append(marker);


        if (item.estado == recusado) {
            map.removeLayer(marker)
        }

    });// fim each
});//fim do get

I belive my problem is that I have a function called atualizaBD which is responsible of changing the icons. That function uses the id of each marker, and from what I can see my id variable is returning two Ids ( the one clicked first and then the second). I'm not sure what's wrong with my code, and why the variable id is returning two diferent ids. Can somebody help me?

Upvotes: 0

Views: 62

Answers (1)

trincot
trincot

Reputation: 350781

The problem is that those three $(document).on("click" statements are executed on every marker click. And this makes the number of click handlers increase each time. The previous ones are not removed.

Instead you should execute those three statements only once, outside of this whole piece of code. You should however then also review the code, so that the variable references you make are still valid after that move.

I cannot judge what exactly you need to change, as it is not clear from your code where you have defined variables like clickedmarker, aceite, concluido, Estado, ...etc, and what their scope is. But certainly you will have to change how you find out what the right value is of item and id. It would probably good to create a global object in which you store information about the current marker (id, ...etc). That way you have a clean, single object, instead of some loose variables.

Upvotes: 1

Related Questions