I'm trying to use Maps JavaScript API with response from Google Maps Directions API to display driving routes passing some waypoints.
I wrote this code below to get waypoints' order using Google Maps Directions API, which is working well.
google_directions.rb
def initialize(origin, destination, waypoints, opts=@@default_options)
@origin = origin
@destination = destination
@waypoints = 'optimize:true' + waypoints
@options = opts.merge({:origin => @origin, :destination => @destination, :waypoints => @waypoints})
@url = @@base_url + '?' + @options.to_query + '&key=' + Rails.application.secrets.google_maps_api_key
@response = open(@url).read
@jdata = JSON.parse(@response)
@status = @jdata['status']
end
def public_response
@response
end
Now, I get json response(@response) from Google Maps Directions API, so I want to reuse it to display the routes on the google map with Maps JavaScript API.
index.html.erb
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw @hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
toRender(<%=raw @response.to_json %>)
});
function toRender(response){
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setDirections(response);
}
</script>
I'm gessing I should pass @response to directionsDisplay.setDirections() as an argument, but it's not working. Could anyone show me the best way to solve this??
I found this Q&A, which says I need to translate the JavaScript API JSON response into a DirectionsResult object. Does anyone know how to do it??
Displaying results of google direction web service without using javascript api
Here is my Google Maps Directions API response from @url request.