2016-11-13 52 views
0

我对编码非常陌生,所以我的代码可能是错误的。我正在使用Mapbox中的flyTo功能从城市飞往城市。我想通过点击按钮飞往多个城市。我已经创建了一个我想要飞到的坐标的数组,但代码似乎没有工作。有人可以帮我解决我出错的地方吗?谢谢!以下是如何使用该功能的页面:https://www.mapbox.com/mapbox-gl-js/example/flyto/在Mapbox中通过坐标循环

var arrayofcoords = [[-73.554,45.5088], [-73.9808,40.7648], [-117.1628,32.7174], [7.2661,43.7031], [11.374478, 43.846144], [12.631267, 41.85256], [12.3309, 45.4389], [21.9885, 50.0054]]; 

document.getElementById('fly').addEventListener('click', function() { 

if(i = 0; i < arrayofcoords.length; i++) { 
map.flyTo(arrayofcoords[i]); 
    }); 
}); 

回答

1

欢迎来到Stackoverflow!

下面是你如何从一个坐标飞到每个按钮点击下一个坐标。请注意,当您到达最后一个坐标时,下一个按钮点击会将您带回第一个坐标。

mapboxgl.accessToken = '<your access token here>'; 

var map = new mapboxgl.Map({ 
    container: 'map', 
    style: 'mapbox://styles/mapbox/streets-v9', 
    center: [-74.50, 40], 
    zoom: 9 
}); 

// This variable will track your current coordinate array's index. 
var idx = 0; 

var arrayOfCoordinates = [ 
    [-73.554,45.5088], 
    [-73.9808,40.7648], 
    [-117.1628,32.7174], 
    [7.2661,43.7031], 
    [11.374478, 43.846144], 
    [12.631267, 41.85256], 
    [12.3309, 45.4389], 
    [21.9885, 50.0054] 
]; 

document.getElementById('fly').addEventListener('click', function() { 
    // Back to the first coordinate. 
    if (idx >= arrayOfCoordinates.length) { 
     idx = 0; 
    } 

    map.flyTo({ 
     center: arrayOfCoordinates[idx] 
    }); 

    idx++; 
}); 

希望得到这个帮助!