A Google Multi-Marker Map Example with Solr, Spring MVC and Thymeleaf

We talked about retrieving multiple locations with Spring Data Solr. We also covered displaying a Google map with Solr, Spring MVC and Thymeleaf. Today we’ll see how to generate a multi-marker Google map, walking through the highlights only. The complete source is in NixMash Spring on GitHub if you’re interested. You can also view the multi-marker map online here.

In the screenshot above you’ll notice in red just below the map a link to an example of handling a malformed Map Coordinates String. We’ll see how to handle any malformed Lat/Lng Strings so we can display a nice message to the user like this.

The Client-side JavaScript

The Multi-Marker Google Map is produced from the GeoLocation Point values of the Products retrieved from our Solr search. Here’s how we’re getting the JSON Product list. Since this is a demo, the search coordinates are in our Controller which we’ll see in a minute. You can see we use the Product’s Point.getX() and .getY() properties to generate the map.

Retrieving Products in the Spring Service Layer

We’re serious about catching bad Lat/Lng values since, unlike our demo, these might be sent to the server as Url Query Parameters. Lots of room for error there, so we created a custom GeoLocationException which we’ll throw at the first sign of trouble.

SolrController and GeoLocationException Handling

The SolrController is where the action is for our demo. Because Path and Request Parameters cannot be optional in Spring MVC methods we created two Urls /products/map and /products/map/bad. Our bad Lat/Lng string is missing a comma (1), (2) is our good Lat/Lng value. In (3) we save the Products returned from our Service Layer to a variable used by the client Ajax Url of /products/json. We also add a “location” Model Attribute which we’ll display on the web page.

Handling the Custom Exception

Upon throwing our custom GeoLocationException we head to our @ControllerAdvice GlobalController class to handle it. At (1) notice how we can work with the “location” Lat/Lng String to display it to our user in an Error Message. That’s because we set the Attribute in the SolrController method above in request.setAttribute(“location”,location);

An important element here is at (2) where we add LOCATION_ERROR_ATTRIBUTE to the Model. The attribute’s name is “mappingError” which we’ll see used in Thymeleaf next.

The Thymeleaf HTML

Here’s the essential Thymeleaf which either loads the Javascript and displays the map or shows the error message. The HTML to display the error message appears first. We can use the presence of the “mappingError” attribute which we created in our GeoLocationException handler above.

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.