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

Viewed 363

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);
}
3 Answers

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

You need to switch your longitude and latitude. This will put the marker in the right place

What seems to be the issue with this is that the marker is being created with the class ".mapboxgl-marker" however it doesn't have any styling so if you add the below CSS you should be able to see the markers.

.mapboxgl-marker {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: red;
}
Related