我如何正确使用带有 setInterval() 或 setTimeout() Javascript 函数的 flyTo()?

How can i properly use flyTo() with setInterval() or setTimeout() Javascript functions?

我在将 Leaflet 函数 flyTo() 与函数 setTimeout() 和 setInterval() 结合使用时遇到了一点问题。

我正在尝试让我的交互式地图以精确的坐标和精确的缩放比例飞越我的国家(克罗地亚)。问题是我无法获得循环飞行路线的代码(萨格勒布 - 奥西耶克 - 斯普利特 - 里耶卡)。

希望有人能给我指出正确的方向:) 谢谢。

我已经尝试在 while 循环和 for 循环中使用计数器,但效果不佳。

<script>
       var intervalZg = setInterval(Zagreb, 5000);
        var intervalOs = setInterval(Osijek, 10000);
        var intervalSt = setInterval(Split, 15000);
        var intervalRi = setInterval(Rijeka, 20000);


        function Osijek(){
            mymap.flyTo([45.554614, 18.696247], 13);        
        }

        function Zagreb(){
            mymap.flyTo([45.806367, 15.982061], 13);            
        }

        function Split(){
            mymap.flyTo([43.511787, 16.440155], 13);
        }

        function Rijeka(){
            mymap.flyTo([45.327369, 14.440395], 13);
        }

        function Pula(){
            mymap.flyTo([44.867527, 13.850097], 13);
        }

        function regijaSjever(){
            mymap.flyTo([45.638587, 17.378766], 8.75);
        }

        function regijaJug(){
            mymap.flyTo()
        }

        function regijaZapad(){
            mymap.flyTo()
        }

    </script>

目前,这段代码确实有效,他要去萨格勒布,然后是奥西耶克,然后是斯普利特,然后是里耶卡,然后回到萨格勒布,在那里它停了下来。

您目前每 5 秒飞往萨格勒布 - 并且每 10 秒飞往奥西耶克等等。因此,当您第一次飞往奥西耶克时 - 您也会呼叫萨格勒布。

也许在每个...中设置下一个位置所以

function Zagreb() {
   mymap.flyTo([45.806367, 15.982061], 13); 
   setTimeout(Osijek, 5000);
}

function Osijek() {
    mymap.flyTo([45.554614, 18.696247], 13);        
    setTimeout(Split, 5000);
}

function Split() {
   mymap.flyTo([43.511787, 16.440155], 13); 
   setTimeout(Rijeka, 5000);
}

function Rijeka() {
    mymap.flyTo([45.327369, 14.440395], 13);
    setTimeout(Zagreb, 5000);
}

Zagreb();

仅使用一个 setInterval 调用的方法如下所示:

// Set up data - an array with the LatLng and the zoom levels for each call

var flights = [
 { latlng: [45.554614, 18.696247], zoom: 13 },
 { latlng: [45.806367, 15.982061], zoom: 13 },
 { latlng: [43.511787, 16.440155], zoom: 13 },
 { latlng: [45.327369, 14.440395], zoom: 13 },
 { latlng: [44.867527, 13.850097], zoom: 13 },
 { latlng: [45.638587, 17.378766], zoom: 8.75 }
];

var flightNumber = 0;

setInterval(function() {

  // flyTo the n-th flight destination...
  map.flyTo( flights[flightNumber].latlng, flights[flightNumber].zoom );

  // The next iteration should fly to the next flight destionation...
  flightNumber++;

  // ...unless we've passed the last flight destination, in which case go 
  // back to the first one.
  // Remember that JS arrays are zero-indexed, so the first element is zero and
  // the last valid element is the (length - 1)-th, hence ">=" instead of ">".
  if (flightNumber >= flights.length) {
    flightNumber = 0;
  }
}, 5000);

当然,这种技术有多种变体,使用不同的数据结构(例如添加名称、没有缩放级别等),并使用模运算符 (%) 而不是检查数组长度(例如 i = i % length)。