Emily Suchy
Emily Suchy

Reputation: 1

Looping through coordinates in Mapbox

I'm pretty new to coding so my code may be wrong. I'm using the flyTo feature in Mapbox to fly from city to city. I want to fly to multiple cities by clicking on the button. I've created an array with the coordinates that I want to fly to, but the code doesn't seem to be working. Can someone help me where I went wrong? Thanks! Here's the page on how to use the feature: https://www.mapbox.com/mapbox-gl-js/example/flyto/ .

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]);
  });
});

Upvotes: 0

Views: 543

Answers (1)

Risan Bagja Pradana
Risan Bagja Pradana

Reputation: 4674

Welcome to Stackoverflow!

Here's how you "fly" from one coordinate to the next coordinate on each button click. Note that when you reached the last coordinate, the next button click will bring you back to the first one.

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++;
});

Hope this help!

Upvotes: 2

Related Questions