Using Google Maps API with Thymeleaf and Spring

We’ve talked about querying and retrieving Solr Location data recently, so it’s time to take it to the next level. We’re going to use that Solr location data, along with Thymeleaf and Spring, to display a map using the Google Maps API.

First let’s see the new Product Page with the location of the product’s store, now in NixMash Spring and shown online here.

There are several good Google Map resources, like the Google Maps JavaScript API Documentation from Google and the W3Schools Google Maps API Tutorial. In this post we’ll only address the issues specific to Spring and Thymeleaf and used in NixMash Spring.

Product Model Location and Point Data Types

In the post Retrieving Location Data with Spring Solr I talked about handling Solr Location data as a String then converting it to a SpringFramework.Geo.Point type as needed. Here are the Location and Point properties of our Product Model.

Thymeleaf Considerations

In the Thymeleaf HTML we load our mapping JavaScript fragment on the condition that the Product contains location data. product.hasLocation() is a method we added to our Product model.

Before we get to the JavaScript Fragment we’ll see the product.hasLocation() condition used again to display the “Location” field and #googleMap Map Container on the Product Details page.

Thymeleaf Inline as Text

Thymeleaf’s Inlining is a very useful tool when populating JavaScript on-the-fly. The Inline we’ll be using is [[${product.location}]] to define the Map Center Latitude and Longitude. (I included the code for using the Product Point values as a reference.)  The Product Location property, a String value as we established, is in the format XXX, XXX making script insertion real easy.

See the first line, th:inline=”text”. It’s important to use “text” to populate Thymeleaf Inline code. Typically we would use “Javascript” when populating Inline within JavaScript. If we were to do so here we would wrap single quotes around the Product Location XXX, XXX value resulting in a single String Lat/Lng value rather than two float values and ultimately a blank map.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.