Using setInterval to eliminate duplicate markers from a leaflet map

I have been working on a Leaflet map project with markers. The markers' latlng data is fetched from JSON and displayed correctly.

I tried using setInterval to refresh the method every 5 seconds to update the latlng positions, ensuring that old markers are hidden and new position markers are shown without duplicates. However, despite trying various options, I have not been successful in achieving this.

The image below illustrates the issue of duplicate aircraft markers on the map when using setInterval to update the positions. Can anyone offer assistance?

https://i.sstatic.net/BH7I4.png

Below is my code:

$(document).ready(function () {

  var markers = {}; // Dictionary to store markers in an outer scope.

  //      Map initialization

  var coords = [33, 44]; // the geographic center of our map
  var zoomLevel = 6; // the map scale.
  var map = L.map('map').setView(coords, zoomLevel);
  L.tileLayer('https://{s}.tile.thunderforest.com/transport-dark/{z}/{x}/{y}.png', {
    attribution: 'Map data ©',
    maxZoom: 18
  }).addTo(map);

  //     Aircraft data

  setInterval(function () {
    $.ajax('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', {
      type: 'GET',
      dataType: 'jsonp',
      timeout: 5000
    }).done(function (data, textStatus, jqXHR) {

      Object.keys(data)
        .map(key => data[key])
        .map((position) => ({
          lat: position[1],
          lng: position[2],
        })).filter(position =>
          position.lat &&
          position.lng &&).forEach(i => {

            if (!markers[i.lat, i.lng]) {
              // Create a new marker if there is no existing one with this id.
              markers[i.lat, i.lng] = L.marker([i.lat, i.lng]).addTo(map);
            }
            markers[i.lat, i.lng].setLatLng(i.lat, i.lng);
          })
    }, 5000)

  });

});

Answer №1

Create a layergroup in Leaflet and then clear it after adding markers.

var markerLayer = L.layerGroup().addTo(map)
setInterval(function(){
            $.ajax('yyyyyyyyyyyyyyyyyyyyyyyyyyyyy', {
                    type: 'GET',
                    dataType: 'jsonp',
                    timeout: 5000
                    }).done(function (result, status, xhr) {
                         markerLayer.clearLayers();
                         markers = {};
                         Object.keys(result)
                            .map(key => result[key])
                            .map((coords) => ({
                                    lat: coords[1],
                                    lng: coords[2],
                            })).filter(coords => 
                                      coords.lat && 
                                       coords.lng &&).forEach(item => {
                            markers[item.lat, item.lng] = L.marker([item.lat, item.lng]).addTo(markerLayer)
                        })
        },5000)

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

The issue of an undefined Node.js variable post "await"

While I know similar questions have been asked before, I assure you that I've gone through them; however, I'm still facing a challenge. I have a simple code snippet to retrieve a token for a 3rd-party API service: let tok = ''; const g ...

Guide on transferring href parameter from the parent Vue component to the child component

Hey there! I've been working on creating a Vue page, breaking it down into components, and populating it with content from json. It all seems pretty straightforward, but I've hit a snag. Why is the href parameter not showing up in the right place ...

Tips for eliminating corner indexes from a 2D array?

Exploring forward ray tracing algorithm using Three.js. I have developed a sample using a 2D array where the Spotlight's location is parsed, but not directly involved. To create lines of sight, I set: startPoint = position of SpotLight endPoint = ...

Eliminate the prior click action from the document object model

I am working with a set of elements that each have unique IDs and contain a span tag with the same image. For example: Under each element, there is a save icon. When a user clicks on it, the icon changes to a non-save icon. The issue arises when I click ...

Issue with installing vscode-ripgrep during VSCode build/run process

After attempting to build and run VSCode on my Ubuntu 17.10 by following the instructions from this guide: https://github.com/Microsoft/vscode/wiki/How-to-Contribute#build-and-run, I encountered an issue when installing dependencies using yarn. The error m ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

Even though setState is supposed to update the state and trigger a render, it's not showing up in the view for some

My React app consists of a simple word/definition feature. There is an edit box that appears for users to change the definition when they click on "edit". Even though I call getGlossary() to update the new definition in the state, I can see the changes in ...

Try utilizing the Array.map method with a two-dimensional array

My current challenge involves a 2-dimensional Array where I am attempting to implement a "randomBool" function on each of the elements within it. The "randomBool" function essentially generates a random boolean value: const randomBool = () => Boolean( ...

Having trouble setting the backgroundImage in React?

Hi there! I'm in the process of crafting my portfolio website. My goal is to have a captivating background image on the main page, and once users navigate to other sections of the portfolio, I'd like the background to switch to a solid color. Alt ...

An error occurred when attempting to set state within a nested fetch

Having difficulty solving an issue with react.js. loadFromServer(pageSize) { fetch('http://localhost:8080/api/employees') .then(response => { return fetch('http://localhost:8080/api/profile/employees', ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

Ways to block past dates on bootstrap date picker starting from the current date and how to prevent dates beyond 90 days in the future from being selected on the

I am currently facing an issue with disabling previous dates from the current date in my code. While the functionality works well for the "From Date" date picker, I am having trouble implementing the same restriction for the "To Date" date picker after 90 ...

Hovering over a table cell triggers a popup in Angular

Inserted a class into <td><span class="only-show-on-hover"></span></td> CSS code for the class td span.only-show-on-hover { visibility: hidden; } td:hover span.only-show-on-hover { visibility: visible; } Code for dialog box < ...

Choose a single checkbox to select all options within a bs-table row

After successfully using bs-tables to pass selected rows through checkboxes, I am now faced with the challenge of sending data from all rows when just one checkbox is selected. The code below depicts my current approach for passing data of single and mul ...

SWR Fails to Recognize Environment Variables

I'm struggling to utilize ENV variables when using the SWR hook for data fetching. My current approach is as follows: const videoURLWithEnv = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCwkj9jcrMZCcbcIa6nF5LNQ&ma ...

Angular model is not receiving the value of a false checkbox

One issue I am facing is with a form that includes a checkbox bound to an ng-model property. The problem arises when the checkbox is checked, as the value gets set in the model. However, when it is unchecked, the key and value remain unset, causing API val ...

The value is undefined until a new Resource object is pushed with the item

I've encountered an issue while testing a factory and I can't seem to find anyone else with the same problem. Can someone help me figure out what's causing this strange error? TypeError: 'undefined' is not a function (evaluating & ...

The data type of Subscription: prototype, NOT ASSIGNED

I am encountering the following error when attempting to return a subscription object. Error Message:-------- Type 'Subscription' does not have the prototype and EMPTY properties that are expected from type 'typeof Subscription' Here ...

Accessing iframe's HTML using a server-side solution by circumventing the Cross-Domain Policy

Our current challenge involves accessing dynamically generated HTML elements using JavaScript, particularly when trying to extract image URLs from these elements. When the HTML elements are generated solely through JavaScript, extracting the URL is straigh ...