0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But I do not think I can move those $(document) because the code that I showed is reference to the buttons inside the infowindow of a marker. Can you give me some hints on how should I do that please? And clickedmarker it represents the marker clicked, and aceite and Estado are both variables that are responsable of changing the icon
Put all variables that relate to the current marker selection in a global, single object (as properties), and keep that object updated whenever a marker is selected. Put everything in it that the three button handlers need. Those should then pick up that info from that single global object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.