Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass json object from java to javascript?

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

In my controller I try 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 is:

[object Object],[object Object]

I explain this in more detail: >

i want use google maps api to display map and draw path coordinated from many lat,longs. i reckon json will be better than list, but i can be wrong.

i try to adjust code from documentation - in code below i try to replace hardcoded coordinates with loop, and values from 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 it's now more clear:)

like image 564
user1199476 Avatar asked Nov 13 '22 08:11

user1199476


1 Answers

myJSON.trackpoints is an array of two objects. If you want to write it as HTML you could do something like this:

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 is really useful when you're using AJAX requests, but for "normal" requests it's better to put plain Java objects into the model, for example:

Spring Controller:

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

JSP:

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

given, that the Coordinate class has the methods getLatitude() and getLongitude(). That method in the Spring controller can even be used for both "normal" and AJAX requests, by using a JSON encoder, like Jackson, and the ContentNegotiatingViewResolver.

like image 99
jabu.10245 Avatar answered Nov 16 '22 03:11

jabu.10245