0

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.

Google Maps Directions API Response

Community
  • 1
  • 1
  • related question: [Show data from Google Directions API on Google Maps](http://stackoverflow.com/questions/21503246/show-data-from-google-directions-api-on-google-maps) – geocodezip Aug 14 '16 at 16:18
  • possible duplicate of [error in displaying Directions webservice result on to the google map](http://stackoverflow.com/questions/35921878/error-in-displaying-directions-webservice-result-on-to-the-google-map) – geocodezip Aug 14 '16 at 16:19
  • Thanks for your help. I added the json response link in the question. – yd0g.sta0203 Aug 15 '16 at 00:08

0 Answers0