Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

javascript - How To Add Markers to a Layer And Display Them Using Leaflet

I want to create multiple markers from a .json asign a Latitude and Longitude from the .json bind a popup which shows Latitude and Longitude and display them in real time, the problem im having is with adding the markers to the layer and displaying it on the map

<script>
        //Creat maps and tiles
        const mymap = L.map('Mapa').setView([0, 0], 5);
        const attribution =
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
        
        const tileUrl= 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
        const tiles=L.tileLayer(tileUrl,{attribution});
        tiles.addTo(mymap);
        
        //Layer
        var markers = L.LayerGroup([])

        //Icono Custom
        const Icono= L.icon({
            iconUrl: 'punto.png',
            iconSize: [32,32],
            iconAnchor: [16,16]
        });
        //Marker
        const marker = L.marker([0,0],{icon:Icono});
        //API
        const api_url= 'https://api.wheretheiss.at/v1/satellites/25544'
        //Function to get data from api
        async function getShip() {
            const response = await fetch(api_url);
            const data = await response.json();
            const { latitude, longitude} = data;                
            marker.setLatLng([latitude, longitude])
            marker.bindPopup("Latitudxa0xa0xa0xa0xa0:xa0xa0"+longitude+"<br>Longitude:xa0xa0"+latitude);
            document.getElementById('lat').textContent= latitude;
            document.getElementById('lon').textContent= longitude;
            markers.addLayer(marker)
        }
    
        getShip();

        L.control.layers(markers).addTo(mymap)


        setInterval(getShip;, 1000);


    </script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to add on every request a new maker you need to create everytime a new marker too:

async function getShip() {
            const response = await fetch(api_url);
            const data = await response.json();
            const { latitude, longitude} = data;    
            //Marker
            const marker = L.marker([latitude, longitude],{icon:Icono}); 
            marker.bindPopup("Latitudxa0xa0xa0xa0xa0:xa0xa0"+longitude+"<br>Longitude:xa0xa0"+latitude);
            document.getElementById('lat').textContent= latitude;
            document.getElementById('lon').textContent= longitude;
            markers.addLayer(marker)
        }

Also I think it should be setInterval(getShip, 1000); instead of setInterval(getShip;, 1000);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...