Nick H
Nick H

Reputation: 245

How can I create multiple Mapbox variables out of a for loop given a list of coordinates

function mapping() {
    var marker0 = new mapboxgl.Marker()
        .setLngLat(mainCoords[0])
        .addTo(map);
    var marker1 = new mapboxgl.Marker()
        .setLngLat(mainCoords[1])
        .addTo(map);
}

How can I have this continue on for as long as mainCoords.length this? I guess the real question is how can I make a bunch of variables with the final piece of is as (i) example: marker(i).

Upvotes: 0

Views: 255

Answers (1)

Ashwin
Ashwin

Reputation: 561

You could just use an array and push all markers in there:

function mapping() {
  var mappings = [];
  var mainCoords= [
      [1, 1],
      [2, 2],
      [3, 3]
    ],
    for (var i = 0; i < mainCoords.length; i++) {
      mappings.push(
        new mapboxgl.Marker()
        .setLngLat(mainCoords[i])
        .addTo(map)
      );
    }
  return mappings;
}

var markers = mapping();
console.log("First marker: ", markers[0]);
console.log("Second marker: ", markers[1]);

Upvotes: 1

Related Questions