Google Maps Display Route From Json
Solution 1:
Given you made a backend request to Directions webservice, and you're passing the complete response to your frontend, you'll need to process the results for them to become a valid DirectionResult object. This is how I'd do it:
if (response.status === 'OK') {
var bounds = new google.maps.LatLngBounds(response.routes[0].bounds.southwest, response.routes[0].bounds.northeast);
response.routes[0].bounds = bounds;
response.routes[0].overview_path = google.maps.geometry.encoding.decodePath(response.routes[0].overview_polyline.points);
response.routes[0].legs = response.routes[0].legs.map(function (leg) {
leg.start_location = new google.maps.LatLng(leg.start_location.lat, leg.start_location.lng);
leg.end_location = new google.maps.LatLng(leg.end_location.lat, leg.end_location.lng);
leg.steps = leg.steps.map(function (step) {
step.path = google.maps.geometry.encoding.decodePath(step.polyline.points);
step.start_location = new google.maps.LatLng(step.start_location.lat, step.start_location.lng);
step.end_location = new google.maps.LatLng(step.end_location.lat, step.end_location.lng);
return step;
});
return leg;
});
directionsDisplay.setDirections(response);
}
Basically, when you use the google.maps.DirectionsService class, the library takes care, on your behalf, to transform to and from two actors:
The routing service (backend Directions API) in charge of providing a route solution for the question "how do I get from A to B"? It makes no assumptions about the way you will use its result.
The drawing service (frontend google.maps.DirectionsRenderer class) in charge of showing the user the visual representation of a generic (but detailed) route. It makes no assumptions on where did you get the routing solution from as long as you feed it the right structure (it is expecting an instance of google.maps.DirectionsResult).
When you chose to use curl or any other server side library to request for directions, you filled the gap to translate the frontend google.maps.DirectionsRequest object into a properly URL encoded Directions API Request. Now you need to translate the Directions API Response back into an instance of google.maps.DirectionsResult.
Even if the JSON result is mostly an object, the renderer does not and should not assume that a plain object should be used to instance paths, routes, positions or legs.
Post a Comment for "Google Maps Display Route From Json"