I've been struggling to pass data from my Spring controller to JavaScript, but I haven't had any success so far. Would using ajax be the best approach for this task? Can you provide me with some hints on how to achieve this effectively?
In my controller, I am attempting to pass the data:
@RequestMapping(value = "/map", method = RequestMethod.GET)
public String map(ModelMap model) {
...
model.addAttribute("trackpoints", json);
return "map";
}
where 'json' is a Gson object (JsonObject) containing:
{"trackpoints":[{"latitude":52.390556,"longitude":16.920295},
{"latitude":52.390606,"longitude":16.920262}]}
In my JSP file, I have:
<script type="text/javascript>
var myJSON = {};
myJSON = ${trackpoints};
document.writeln(myJSON.trackpoints);
</script>
However, the result appears as:
[object Object],[object Object]
To elaborate further:
I want to use the Google Maps API to display a map and draw path coordinates using multiple latitude and longitude points. I believe using JSON would be more efficient than a list, but I could be mistaken.
I attempted to modify code from the documentation - in the code below, I tried to replace hardcoded coordinates with a loop that extracts values from the JSON object.
<script type="text/javascript>
function initialize() {
var myLatLng = new google.maps.LatLng(0, -180);
var myOptions = {
zoom : 3,
center : myLatLng,
mapTypeId : google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892) ];
var flightPath = new google.maps.Polyline({
path : flightPlanCoordinates,
strokeColor : "#FF0000",
strokeOpacity : 1.0,
strokeWeight : 2
});
flightPath.setMap(map);
}
</script>
I hope this explanation clarifies things :)