Search code examples
javascriptfor-loopmapboxmapbox-gl

MapBox GLJS - Markers aren't showing up when created using for loop


I am using the MapBox GL JS API and I am trying to loop through an array containing arrays of marker data to create a bunch of markers. When I iterate through the data and print it to the console, it works with no errors. When I run the code below, there are also no errors but the markers don't show up. What do I need to fix/change so the markers show up?

My code:

if (!mapboxgl.supported()) {
  alert("Your browser does not support Mapbox GL!");
}

// map initialization
var map = new mapboxgl.Map({
  container: 'map', // container id
  style: 'mapbox://styles/mapbox/streets-v11', // style URL
  center: [-121.91, 37.7], // starting position [lng, lat]
  zoom: 6 // starting zoom
});

// test marker
var marker = new mapboxgl.Marker({
  color: "#FFFFFF",
  draggable: false
  }).setLngLat([-121.91, 37.7])
  .setPopup(new mapboxgl.Popup().setHTML("<h3>Dublin, CA</h3>"))
  .addTo(map);

// import markers for all the restaurants
// separate colors for "clean" restaurants and "violation" restaurants
// info needed from csv files: id#, restaurant name, cords, and violation type (if applicable)

var mapdata = [[2359228,'MINGHIN STRETEREVILLE',41.89246018674152,-87.62203678900627], [2356848,'OASIS FRESH FOOD INC.',41.93297686391123,-87.64149608965117], [2356434,'SIMPLY THALIA',41.88342263701489,-87.62802165207536]];
var mapdatalength = mapdata.length;

for (var i = 0; i < mapdatalength; i++) {
  var marker = new mapboxgl.Marker({
    color: "#e74c3c",
    draggable: false
    }).setLngLat([mapdata[i][2], mapdata[i][3]])
    .setPopup(new mapboxgl.Popup().setHTML(mapdata[i][1]))
    .addTo(map);
}

Solution

  • I think you have the latitude and longitude switched in your code. Try reversing them and see if that works