So I have a button search, which dynamically shows hotels. I want next to them I want to show a map. For the time being I have the same lat and long for all hotels so I expect to see the same map. However, currently I see only one map generated for the first hotel. The rest are blank. What am I doing wrong?
Here is the code:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script th:inline="javascript">
function initMap() {
fetch('http://localhost:8080/accommodations')
.then(response => {
return response.json()
})
.then((data) => {
console.dir(data)
data.forEach(function (hotel) {
console.log(hotel);
const coords = {
lat: parseFloat(hotel.lat),
lng: parseFloat(hotel.lng)
};
console.log(coords);
const map = new google.maps.Map(
document.getElementById('map'), {zoom: 15, center: coords});
const marker = new google.maps.Marker({position: coords, map: map});
})
})
}
</script>
<script type="text/javascript" th:inline="javascript">
document.getElementById('showAll').addEventListener('click', showAll);
function showAll() {
// window.addEventListener('DOMContentLoaded', (event) => {
fetch('http://localhost:8080/accommodations')
.then(response => {
return response.json()
})
.then((data) => {
console.dir(data)
let output = '<h2 style="padding-left: 27px"> Search Results </h2>'
data.forEach(function (hotel) {
console.dir(hotel)
initMap();
output += `
<div class="col-lg-3 px-0" id="map"></div> `;
});
document.getElementById('output').innerHTML = output
})
}