An issue with duplicate markers in Leaflet causing problems with removing layers

I've encountered a issue with my Ajax function in the Laravel project I'm working on. The function retrieves data from a database and displays it on a Leaflet map. However, when I use setInterval, the markers on the map start to duplicate. I've tried using removeLayer but it doesn't seem to resolve the problem.

Here is the code snippet:

 function callAjax() {
        $.ajax({
            url: '/device_new',
            type: 'GET',
            dataType: 'json',
            success: function(data) {    
                markerLayer.removeLayer(); 
                var markerLayer = L.featureGroup().addTo(map);
                var coordinates = data;
                for (var i = 0; i < coordinates.length; i++) {
                    if (coordinates[i].x && coordinates[i].y) {
                        marker = L.marker([coordinates[i].x, coordinates[i].y])
                            .bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)

                        marker.addTo(markerLayer);
                    }
                }

                map.fitBounds(markerLayer.getBounds());

            },

        });
        setInterval(callAjax, 3000);
    }

Does anyone have any suggestions on how to fix this issue?

Answer №1

deleteLayer(<Layer>) is used to eliminate a specific layer from the featureGroup.

If you want to delete all layers at once, you should use

markerLayer.clearLayers()

This will clear out all existing layers.

Answer №2

Make the necessary adjustments in your code:

 function updateAjax() {
        $.ajax({
            url: '/device_update',
            type: 'GET',
            dataType: 'json',
            success: function(data) {    
                markerLayer.clearLayers();

                var coords = data;
                for (var j = 0; j < coords.length; j++) {
                    if (coords[j].lat && coords[j].lon) {
                        mark = L.marker([coords[j].lat, coords[j].lon])
                            .bindPopup("Device Type: " + coords[j].type + '<br>' + "Timestamp: " + coords[j].timestamp)

                        mark.addTo(markerLayer);
                    }
                }

                map.fitBounds(markerLayer.getBounds());

            },

        });
        setInterval(updateAjax, 2500);
    }


function displayMap() {
            // Define where to show the map.
            var view = document.getElementById('leaflet-map');

            // Set dimensions. CSS can also handle this.
            view.style = 'height:385px;', 'width:500px;';

            // Generate Leaflet map on given element.
            map = L.map(view);

            // Include OSM tile leayer on the map.
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);

            map.pm.addControls({
                position: 'topright',
            });

//********************** INCLUDE HERE **************    
        var markerLayer = L.featureGroup().addTo(map);  

        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to transfer ID to a different HTML page

I have some Javascript code in a file named nextPage.js. When this code is executed by clicking on something, it should transfer the value of category_id to another page called reportlist.html. Can you please provide assistance with this? var base_url = " ...

Error message: The ScriptResource failed to load

This issue is puzzling... I have an ASP.NET 3.5 web application that consists of a content page and a master page, with a few user controls added on the content page. In total, there are four controls on the page - two custom controls and two Ektron CMS ...

updating container with wire:ignore in laravel livewire

Incorporating a Vue component into a Livewire component, specifically using a DatePicker component: <div id="customDiv" class="col-12 col-md-6 m-1" wire:ignore> <date-picker v-model="date" ...

Unable to close modal after receiving ajax response

Utilizing mdbootstrap for my current project has been a great experience. One area that I am struggling with is implementing an AJAX call upon checking a checkbox, where I expect a response from PHP indicating success (1) or failure (0). However, despite d ...

Utilizing AJAX to call a partial view

Here is the snippet of code showing my ajax call to a partial view after some processing: function fetchData(data) { $.ajax({ url: "/Orders/DraftOrderDetailsLineItems", type: 'GET', cache: false, dataType: 'html', d ...

Sending an array or list of files from AJAX to the Controller

I have a task to upload multiple files and pass them to my Controller's Action. The current code is functional, but I feel there could be room for improvement as it's somewhat manual. I need to display file upload elements based on the number of ...

PHP: Communicating Data with JavaScript

What if my PHP script requires some time to complete its operations? How can I keep the client updated on the progress of the operation, such as during a file download where the estimated time and data size need to be communicated? In PHP, calculating all ...

The webpage continues to refresh after executing a JavaScript function triggered by the AJAX response

I have experimented with various solutions for calling a JavaScript function returned from an AJAX response. While each method worked to some extent, I found that using an alert within the refreshResults function was necessary in order to display the resul ...

JSON: Automatically choose the radio button based on the provided response

Is there a way to automatically select the checked state of radio buttons based on data retrieved from a database? I need to populate this form's radio button with data <div class="col-md-4"> <label> <input type="radio" name="m ...

Having trouble with the Ajax load function not functioning in your HTML code?

The issue has been resolved. Thank you to everyone who helped! Initially, I was attempting to run a file offline instead of on a web server (XAMPP server). Once I uploaded the file to the web server, it started working properly. I had been trying to load ...

Doctrine's implementation of Many-To-Many Relationships

Having just started with Symfony, I am currently developing a movie website that allows users to create movies and associate them with actors. I have successfully set up the relationship using Doctrine, and I can see all the created movies. However, I am f ...

Is it possible to utilize the .load() method in JQuery to handle form processing?

Seeking guidance on a technical matter here. Despite my efforts to find an answer online, I have yet to come across a solution. The scenario is this: there's an ASPX page labeled form.aspx, containing a form along with the necessary code behind logic ...

Uncover the mysteries of the pyramid and json

I am developing a web app using Pyramid that involves fetching data from the user, retrieving information from the backend based on the input values, and then displaying the results in a table format. The process includes the following steps: User enters ...

The Ajax Control Upload consistently defaults to the default value and disregards any text input selected from the drop-down list

On my website, I have implemented an ajax control upload event that allows users to upload a zip file and then unzip it using zlib. The folder name for unzipping is created based on the selection from a dropdown list. However, I am facing some issues where ...

The AJAX request for JSON data is functioning correctly in Firefox, but is experiencing compatibility issues with other web browsers

I recently completed a PHP page that generates a valid JSON document. The jQuery code used to fetch and display the data is quite straightforward: $.ajax({ url: "http://localhost:8888/rkm/json-jc", dataType: "json", success: function(data) { ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Guide on incorporating a dynamic star rating system for products

I've been struggling to incorporate star ratings for my products, but I keep encountering an error. I've fetched both the product and rating data from MySQL, but it's not functioning properly. Below is my code – kindly assist me: //rating ...

Guide to implementing jQuery autocomplete with an AJAX request to a PHP file

I'm currently working on implementing a jQuery autocomplete feature, and here is the code I have so far: $( "#text" ).autocomplete({ source: function( request, response ) { $.ajax({ type: 'GET', url: ' ...