How to pass json object from java to javascript?

I am trying to pass data from spring controller to javascript but no luck. Should I use ajax for this? Please, could you give me some advice on how to do this? What is the best way?

In my controller, I am trying to pass 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>

but the result:

[object Object],[object Object]

I explain this in more detail:>

I want to use google maps api to display a map and draw a path coordinated with many long armor. i reckon json will be better than a list, but I could be wrong.

I am trying to customize the code from the documentation - in the code below, I am trying to replace the hard-coded coordinates with the outline and 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>

Hopefully this will become clearer now :)

+5
2

myJSON.trackpoints - . HTML, - :

function writeCoordinates(coords) {
    document.writeln('<div>lat = ' + coords.latitude);
    document.writeln(', lon = ' + coords.longitude + '</div>');
}

int len = myJSON.trackpoints.length;
for (int i = 0; i < len; i++) {
    writeCoordinates(myJSON.trackpoints[i]);
}

BTW: JSON , AJAX, "" Java , :

Spring :

List<Coordinate> trackpoints = ...
model.addAttribute("trackpoints", trackpoints);

JSP

<c:forEach items="${trackpoints}" var="coord">
    <div>lat = ${coord.latitude}, lon = ${coord.longitude}</div>
</c:forEach>

, Coordinate getLatitude() getLongitude(). Spring "", AJAX-, JSON-, Jackson, ContentNegotiationViewResolver.

+1

: http://jsfiddle.net/AHue8/4/

, , , - , , . "trackPoint" ( , ), , , , .

0

All Articles