Map markers multiplying when use setInterval

Asked

Viewed 44 times

-1

I would like to understand why my map markings are multiplying when I use setInterval to update geolocation.

 <!DOCTYPE html>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
        integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
        crossorigin="" />

    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
        integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
        crossorigin=""></script>


    <title>Geolocalização</title>
</head>

<body>





    <div id="map" style="height: 480px;"></div>

    <script>

        const map = L.map('map').setView([0, 0], 2);

        L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=hcnXSMrp54vKga2aCeyL', {
            attribution: '<a href="https://www.ifvarb.com/" target="_blank">Infinite Flight Aero Brasilps://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>',
        }).addTo(map);

        const myIcon = L.icon({
            iconUrl: 'iss.png',
            iconSize: [50, 32],
            iconAnchor: [25, 16],

        });


        const url_api = 'http://infinite-flight-public-api.cloudapp.net/v1/Flights.aspx?apikey=78879b1d-3ba3-47de-8e50-162f35dc6e04&sessionid=7e5dcd44-1fb5-49cc-bc2c-a9aab1f6a856'

        async function getIss() {

            const response = await fetch(url_api);
            const data = await response.json();
            let array = data.filter(x => x.DisplayName.includes("IFAB"));

            for (i in array){

            const latitude = array[i].Latitude
            const longitude = array[i].Longitude



            L.marker([latitude, longitude]).addTo(map);

        }


            };                


        getIss()

        setInterval(getIss, 5000)
    </script>

</body>

</html>

1 answer

1


You will have to remove them before adding. An easy way to do this is by using the Layergroup:

...
layerGroup = L.layerGroup().addTo(map);
async function getIss() {

  const response = await fetch(url_api);
  const data = await response.json();
  let array = data.filter(x => x.DisplayName.includes("IFAB"));

  //remove todos os markers antes de adicionar
  layerGroup.clearLayers();

  for (i in array){
    const latitude = array[i].Latitude
    const longitude = array[i].Longitude

    //L.marker([latitude, longitude]).addTo(map);
    //ao invés de adicionar no mapa, adicione no grupo
    L.marker([latitude, longitude]).addTo(layerGroup);

 }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.