简体   繁体   中英

Pass data from Bean to javascript on jsf page. Google api directions

I need to pass waypoints to google maps javascript directions api from ManagedBean to jsf page. I'm trying to make JSONArray and pass it to jsf:

private JSONArray routesJSON;

with getters and setters.

Than im creating JSON : in loop im adding Strings with LatLang of waypoints to List<String>

routes.add("new google.maps.LatLng(" + o.getLatitude() + "," + o.getLongitude()+")");

And im getting JSON :

[{"location":"new google.maps.LatLng(50.495121,22.1705)"},{"location":"new google.maps.LatLng(50.57082,22.06813)"},{"location":"new google.maps.LatLng(50.570549,22.047871)"},{"location":"new google.maps.LatLng(50.521389,21.912695)"},{"location":"new google.maps.LatLng(50.495121,22.1705)"}]

from:

for()
array.put(obj);
}
System.out.println(array);

in JSF function for displaying route : (it works with hardcoded data)

function calcRoute() {

              var waypts = [];                 
              var start = new google.maps.LatLng(#{someBean.startLatitude}, #{someBean.startLongitude});            
              var end = new google.maps.LatLng(49.712112, 21.50667);
              var way = #{someBean.routesJSON};
              var request = {
              origin:start,
              destination:end,
              optimizeWaypoints: true,                        
              waypoints:way;         
              travelMode: google.maps.TravelMode.DRIVING
              };
              directionsService.route(request, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(result);
                }
              });
            }

But when im displaying that page map doesnt appear. I know it's probably because of " in JSON but i dont know how to remove it. Or may there are easiest ways to pass waypoint data from Bean to jsf page?

Instead of returning a JSON data packet that contains javascript statements like "new google.maps.LatLng(50.495121,22.1705)", it's more sensible to return just the coordinates.

So if you had a JSON packet that looks like this in your javascript (I don't know how to pass data between your Java and Javascript):

var routes = [
  {"lat":"50.495121", "lng":"22.1705"},
  {"lat":"50.57082", "lng":"22.06813"},
  {"lat":"50.570549", "lng":"22.047871"},
  {"lat":"50.521389", "lng":"21.912695"},
  {"lat":"50.495121", "lng":"22.1705"}
]

You can turn this into an array like so:

var way = [];
for (var i = 0; i < routes.length; i++) {
  way.push(new google.maps.LatLng(parseFloat(routes[i].lat), parseFloat(routes[i].lng)));
}

NB: the use of parseFloat to convert strings like "50.495121" into floating point numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM