Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I am trying to show multiple maps with coordinates fetched from the DB.

However what I have so far gives me error "expected mapdiv of type htmlelement but was passed null.". I am not sure why am I getting this and not sure how to fix it so any help is appreciated..

JavaScript
<script>
   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(hotel);
   
                   output += `
       <div class="hotel py-4 px-2 pb-4 border-bottom">
           <div class="row justify-content-center">
           
               <div class="col-lg-3 px-4">
                   <img src= ${hotel.imageUrl}
                       height="200" width="250" alt="" class="hotel-img rounded">
               </div>
               
               <div class="col-lg-3 px-0" id="map" ${initMap(hotel)}>
               </div>
               
           </div>
       </div>`;
               });
   
               document.getElementById('output').innerHTML = output
           })
   }
   
</script>
<!-- ======= Footer ======= -->
<footer th:replace="fragments/footer::footer"></footer>
<!-- End Footer -->
<script async defer
   src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script th:inline="javascript">
   function initMap(hotel) {
   
       let lng = hotel.lng;
       let lat = hotel.lat;
       console.log(lng);
       console.log(lat);
   
   
       const coords = {
           lat: parseFloat(lat),
           lng: parseFloat(lng)
       };
   
   
       const map = new google.maps.Map(document.getElementById("map"), {zoom: 15, center: coords});
       const marker = new google.maps.Marker({position: coords, map: map});
       }
   
   
</script>
</body>
</html>


What I have tried:

I moved initMap(hotel) from just below data.forEach function into the div with id=map but I get the same error.
Posted
Comments
Richard MacCutchan 23-Apr-22 12:17pm    
The error tells you that some reference has not been correctly initialised. You need to do some debugging to find out why.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900