I've been trying to get use Mapbox GL JS to plot multiple markers and have the map fitBounds on those markers. The markers plot fine on the map, Im just having trouble with the fitBounds part.
I keep on getting this console error:
Uncaught TypeError: Cannot read property 'lng' of undefined
lng_lat_bounds.js:154
Here is my JS to plot the markers.
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [-96.2, 37.8],
zoom: 9
});
// add markers to map
var bounds = new mapboxgl.LngLatBounds();
for ( var i=0; i < markersArray.length; ++i ){
markersArray[i].features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add it to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({offset: 25}) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
});
}
map.fitBounds(bounds);