I am trying to pass latitude and longitude data from a MySQL database through my Spring Boot application into a javascript function. I was able to use Thymeleaf to display a table on the webpage with the data, so I know the service and controller classes are set up correctly.
Below shows how my table is populated:
<table style="word-wrap:break-word;white-space:normal;" >
<thead >
<tr>
<th>Latitude</th>
<th>Longitude</th>
<th></th>
</tr>
</thead>
<tbody>
<th:block th:each="point : ${listPoints}">
<tr>
<td>[[${point.LAT}]]</td>
<td>[[${point.LNG}]]</td>
</tr>
</th:block>
</tbody>
</table>
I also hard coded the params of my javascript function which works. Below is the js function:
addMarker({lat:50.772775,lng:3.889969});
function addMarker(coords) {
var marker = new google.maps.Marker({
position: coords,
map:map
})
}
I need a way to loop through my lat and lng's to add a marker for each. Thank you!
CodePudding user response:
Suppose you have a class Point
:
public class Point {
double lat;
double lng
// getters omitted
}
Further your servlet/controller passes a list of points as attribute listPoints
to the Thymeleaf page, so that it shows in your table:
<tbody>
<th:block th:each="point : ${listPoints}">
<tr>
<td>[[${point.lat}]]</td>
<td>[[${point.lng}]]</td>
</tr>
</th:block>
</tbody>
In your JavaScript (wherever this lays) you have to call the addMarker
function for each of all those coordinates.
For example:
addMarker({lat:50.772775,lng:3.889969});
for the first point and so on.
You could pass the points inside a javascript-inlining block to your Thymeleaf page:
<script th:inline="javascript">
var points = /*[[${listPoints}]]*/ null;
console.log(points); // just a debug print to verify all points received
points.forEach(p => addMarker(p));
</script>
Now you have to make sure that this script with populated points is loaded in the correct order (when addMarker
function is ready to add markers on the map). You can also wrap this inside a function that is invoked onload
.
See also: