Search code examples
javascriptjavajqueryspring-bootthymeleaf

GoogleMap API with Java/Springboot and Thymeleaf receiving the coordenates but not creating the map


I'm creating a web aplication in JAVA/SPRING/HTML5 with Thymeleaf that makes a map with markers based on a H2 Database with latitude and longitude of all customers. I was successful in the backend x front integration. The Java controller send a object to HTML page with Thymeleaf, that page import a javascript file with a google map generate function, consuming the object and executing the function. But the problem is: the map do not generate on the page

I debug the code and dont figure out whats the problem.

HTML CODE (I reduce the code to focus on the problem):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Mapa do cliente</title>
</head>
<body>
        <div class="mapa"
            th:attr="data-latitude=${customer.latitude},data-longitude=${customer.longitude}"
            id="map" style="width: 100%; height: 100%"></div>
    <script src="https://jquery.gocache.net/jquery-3.5.1.min.js"
        type="text/javascript"></script>
    <script src="/webjars/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=&v=weekly"></script>
    <script src="/js/mapFunctions.js"
        type="text/javascript"></script>

</body>
</html>

JAVASCRIPT CODE:

let map;
var lat = $('.mapa').attr('data-latitude')
var lng = $('.mapa').attr('data-longitude')
    function initMap(lat, lng) {
            map = new google.maps.Map(document.getElementById("map"), {
                center: { lat, lng },
                zoom: 8
            });
        }
initMap(parseFloat(lat), parseFloat(lng))

I print the 'lat' and 'lng' variables in console and they are ok. Im not a expert in javascript and english, so excuse-me whatever not good pratice.


Solution

  • Appears to be a style problem. How was not renderizing the map, i tryed to change the height and witdh of 100% to 500px in <div id="map">, and the maps showed up. So, the code above really attends its purpose, if the change are make. Sure there is better prattices, but for didatic way i think its a valid contribution. Thanks for the help guys.