简体   繁体   中英

How can I Keep a moving object centered on Leafllet?

I have positioned this satellite on a leaflet map, it is changing locations every 5 seconds. I want to keep the moving object centered on the map so it does not get lost and disappear from sight. here is HTML and JS code:

JS

 var map = L.map('map').setView([0,0], 2); function moveISS () { $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function(data) { var lat = data['iss_position']['latitude']; var lon = data['iss_position']['longitude']; iss.setLatLng([lat, lon]); isscirc.setLatLng([lat, lon]); map.panTo([lat, lon], animate=true); }); setTimeout(moveISS, 5000); } var styled = L.gridLayer.googleMutant({ type: 'roadmap', styles: [ {elementType: 'labels', stylers: [{visibility: 'off'}]}, {featureType: 'water', stylers: [{color: '#444444'}]} ] }).addTo(map); var roads = L.gridLayer.googleMutant({ type: 'terrain' // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid' }).addTo(map); L.terminator().addTo(map); //L.terminator().addTo(map);// //http://static-cdn2.ustream.tv/favicon.ico// //https://www.n2yo.com/inc/saticon.php?t=0&s=25544 //L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);// var ISSIcon = L.icon({ iconUrl: 'file:///C:/Users/rez/Downloads/noun_24414.svg', iconSize: [50, 30], iconAnchor: [25, 15], popupAnchor: [50, 25], shadowUrl: 'file:///C:/Users/rez/Downloads/noun_24414.svg', shadowSize: [30, 20], shadowAnchor: [15, 8] }); var iss = L.marker([0, 0], {icon: ISSIcon}).addTo(map); moveISS(); 
 <p id="isstime">WHERE IS ISS?</p> <br> <div id="map"> </div> <script src="iss.js"> </script> <br> 

I removed some parts of your code and modified the moveISS function a little:

var map = L.map('map').setView([0, 0], 4);

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

function moveISS() {
  $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function(data) {
    var lat = data['iss_position']['latitude'];
    var lon = data['iss_position']['longitude'];
    iss.setLatLng([lat, lon]);
    map.panTo([lat, lon], {animate: true});
  });
  setTimeout(moveISS, 5000);
}

var iss = L.marker([0, 0]).addTo(map);
moveISS();

The moving marker is kept centered on the map.

Check it out in this JSBin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM