Mixer2 - the java/xhtml template engine - is compliant to inline JavaScript. https://github.com/nabedge/googlemap-mixer2-sample is a sample project using Google Maps API, Spring MVC, and Mixer2. I describe the code and some tips.
First, look at the map.html, a template html file for Mixer2. This html is almost a copy of google official hello world sample.
The difference is one code.
before:
center: new google.maps.LatLng(-34.397, 150.644),
after:
center: new google.maps.LatLng(defaultValues.lat, defaultValues.lng),
and one script tag is added.
The point is that the "data" and "program" is separated into each <script> tags.
Next, the controller of Spring MVC, IndexController. Controller create the model having start latitude and longitude values and pass it to view;
@RequestMapping(value = "/") public String map(Model model) { log.debug("showing map()..."); MaplatLngMap = new HashMap (); latLngMap.put("lat", 35.633302); latLngMap.put("lng", 139.799652); model.addAttribute("latLngMap", latLngMap); return "mapView"; }
The view is MapView class.
import com.google.gson.Gson; // snip... // load html template String mainTemplate = "classpath:m2mockup/m2template/map.html"; Html html = getMixer2Engine().loadHtmlTemplate( resourceLoader.getResource(mainTemplate).getInputStream()); // snip... MaplatLngMap = (Map ) model.get("latLngMap"); // set default value for google maps api Gson gson = new Gson(); Script script = html.getHead().getById("defaultValuesJson", Script.class); script.setContent("var defaultValues = " + gson.toJson(latLngMap) + ";");
You should look that the content of <script id="defaultValuesJson"> tag is replaced by the new json strings using mixer2 tag object and methods.
You get the result of browser:
.....
THE POINTS:
- You can write map.html on local editor. The JavaScript code can run without deploying application server. You can see the map on browser. If you use JSP and write the code like "center: new google.maps.LatLng(<%=startLat%>, <%=startLng%>)", Your code can not run it as JavaScript !
- Using Mixer2 as template engine, you should separate "data" and "program" in your JavaScript code on the template and put them into each <script> tags. On the server side, replace only <script> tag having the "data".
No comments:
Post a Comment