I have an array of address data, and I would like to know, how would I add multiple markers to my Mapbox map? I am pretty sure I would somehow have to loop through my array, but I am not sure how would I add it to my map, if it is at all possible. Here is my code:
var streetArray = JSON.stringify(<%- streets %>);
var cityArray = JSON.stringify(<%- cities %>);
var countryArray = JSON.stringify(<%- countries %>);
var zipArray = JSON.stringify(<%-zips %>);
var streetValue = JSON.parse(streetArray);
var cityValue = JSON.parse(cityArray);
var countryArray = JSON.parse(countryArray);
var zipValue = JSON.parse(zipArray);
mapboxgl.accessToken = //my_access_token
const mapboxClient = mapboxSdk({ accessToken: mapboxgl.accessToken });
mapboxClient.geocoding
.forwardGeocode({
query: streetValue[6].value + " " + cityValue[6].value + " AZ " + zipValue[6].value,
autocomplete: false,
limit: 1
})
.send()
.then((response) => {
console.log(streetValue[6].value + " " + cityValue[6].value + " AZ " + zipValue[6].value);
if (
!response ||
!response.body ||
!response.body.features ||
!response.body.features.length
) {
console.error('Invalid response:');
console.error(response);
return;
}
const feature = response.body.features[0];
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: feature.center,
zoom: 10
});
// Create a marker and add it to the map.
new mapboxgl.Marker().setLngLat(feature.center).addTo(map);
});
I understand that setLngLat adds the marker to the map, but I think I need to make multiple calls to the API in order to add more than one. How would I do this with my code?