如何将移动物体保持在Leafllet的中心?

时间:2018-03-17 08:48:27

标签: javascript leaflet

我已将此卫星定位在传单地图上,它每5秒更换一次位置。我希望将移动物体保持在地图的中心位置,这样它就不会迷失并从视线中消失。这是HTML和JS代码:

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>

1 个答案:

答案 0 :(得分:1)

我删除了代码的某些部分并稍微修改了moveISS函数:

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();

移动标记在地图上保持居中。

查看in this JSBin