0

I have written code to fetch data from the database displayed in a table. I want to fetch the longitude and latitude so I can display multiple markers via the Google Maps API. Currently I have a marker with a hardcoded longitude and latitude values. I assume a for loop will have to be used to fetch the latitude and longitude values in order to pass the data to the markers.

Here's the code I currently have for the map. I have hardcoded coordinates for the marker.

<div id="map"></div>

    <script th:inline="javascript">
    /*<![CDATA[*/
    function initMap() {
        // The location of the map
        var map = new google.maps.Map(document.getElementById('map'),
        {center:{ lat: 51.903614, lng: -8.468399 }, zoom: 12 });

        var marker = new google.maps.Marker({
        position: { lat: 51.903614, lng: -8.468399 },
        map: map,
        title: 'Hello World',
        animation: google.maps.Animation.BOUNCE,
        animation: google.maps.Animation.DROP
        });
    }
    /*]]>*/
    </script>

This is the table that I created to fetch all of the data that I have from the database.

<div>
<table border="1">
    <tr>
        <th>ID</th>
        <th>Sample</th>
        <th>Longitude</th>
        <th>Latitude</th>
        <th>Sound Level</th>
    </tr>
    <tr th:each = "sample: ${samples}">
        <td th:text="${sample.id}"></td>
        <td th:text="${sample.sample}"></td>
        <td th:text="${sample.longitude}"></td>
        <td th:text="${sample.latitude}"></td>
        <td th:text="${sample.db}"></td>
    </tr>
</table>
Chewie
  • 11
  • 1

1 Answers1

0

You can iterate through your Thymeleaf model variable in a JavaScript code block like this:

<script th:inline="javascript">
    
    function initMap() {
        // The location of the map
        var map = new google.maps.Map(document.getElementById('map'),
        {center:{ lat: 51.903614, lng: -8.468399 }, zoom: 12 });

        /*[# th:each="sample : ${samples}"]*/
            var marker = new google.maps.Marker({
                position: { lat: [[${sample.latitude}]], lng: [[${sample.longitude}]] },
                map: map,
                title: 'Hello World',
                animation: google.maps.Animation.BOUNCE,
                animation: google.maps.Animation.DROP
                });
  
        /*[/]*/
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211