title: Rendering routes with GoogleAPI JS
body: <p>I was following along with a tutorial involving the GoogleMaps API JS, and everything went well. When trying to building my own app I've come across an issue with displaying a route. The application I'm working on is mainly written in ruby on rails.</p>
  
  <p>The "pseudo code" problem is when clicking on to "view route" button, the route is not displaying on the map.</p>
  
  <p>Below is the HTML that triggers the first event when clicking on the search with in time button, and the CSS as requested.</p>
  
  <pre><code>&lt;body&gt;
   &lt;div&gt;
      &lt;span class="text"&gt; Within &lt;/span&gt;
      &lt;select id='max-duration'&gt;
        &lt;option value="10"&gt;10 min&lt;/option&gt;
      &lt;/select&gt;
      &lt;select id="mode"&gt;
        &lt;option value="DRIVING"&gt;drive&lt;/option&gt;
      &lt;/select&gt;
      &lt;span class="text"&gt;of&lt;/span&gt;
      &lt;input id= 'search-within-time-text' type='text' placeholder='Your Location'&gt;
      &lt;input id= 'search-within-time' type='button' value='Go'&gt;
    &lt;/div&gt;
   &lt;div id="map"&gt;&lt;/div&gt;
   &lt;script src="https://maps.googleapis.com/maps/api/js?libraries=places,drawing,geometry&amp;key=&lt;%= ENV["MAP_API"] %&gt;&amp;v=3"&gt;&lt;/script&gt;
  &lt;/body&gt;
  
  &lt;style&gt;
    #map {
     bottom: 0px;
     height: 500px;
     left: 362px;
     position: absolute;
     right: 0px;
    }
  
   .container {
    height: 500px;
    position: relative;
   }
  
   .options-box {
    background: #fff;
    border: 1px solid black;
    height: 91.75%;
    line-height: 35px;
    padding: 10px 10px 30px 10px;
    text-align: left;
    width: 340px;
   }
  
   #zoom-to-area-text{
    width:200px;
   }
  &lt;/style&gt;
  </code></pre>
  
  <p>The location array that is stroing the data is found in the maps controller, where we are pushing data from our SQLite DB.</p>
  
  <pre><code>def index
  @test_array = []
  @test.each do |h|
    @test_array.push({lat: h.lat, lng: h.lng})
    end
  end
  </code></pre>
  
  <p>In particular I believe the problem lays within the function displayDirections. Which can be found at the bottom of the full code</p>
  
  <p>The displayDirections function is written outside of the initMap function, because of a scoping issue when it is written inside of the initMap function. I've read the problem below</p>
  
  <p><a href="https://stackoverflow.com/questions/9309285/google-maps-api-directions-result-not-showing">Maybe a similar issue</a></p>
  
  <p>But had issues with displayDirections being defined at the click event, when it was written with in the initMap function, in the function displayMarkersWithinTime.</p>
  
  <p>Any help is appreciated! Thanks!</p>
  
  <pre><code>function initMap() {
   var map;
   var markers = [];
   var placeMarkers = [];
  
   document.getElementById('search-within-time').addEventListener('click', function(){
    searchWithinTime();
   });
  
   map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 39.9523789, lng: -75.1635996},
    zoom: 13,
    mapTypeControl: false
   });   
  
   var locations = &lt;%= raw @test_array.to_json%&gt;
  
   for (var i = 0; i &lt; locations.length; i++) {
    var position = locations[i]
    var marker = new google.maps.Marker({
     position: position,
     animation: google.maps.Animation.DROP,
     id: i
     });
     markers.push(marker); 
    } 
  
   function hideMarkers(markers) {
    for (var i = 0; i &lt; markers.length; i++){
     markers[i].setMap(null);
    }
   }
  
   function searchWithinTime(){
    var distanceMatrixService = new google.maps.DistanceMatrixService;
    var address = document.getElementById('search-within-time-text').value;
    if (address == ''){
     window.alert('You must enter an address.');
    } else {
     hideMarkers(markers);
     var origins = [];
     for (var i = 0; i &lt; markers.length; i++) {
      origins[i] = markers[i].position;
     }
     var destination = address;
     var mode =  document.getElementById('mode').value;
     distanceMatrixService.getDistanceMatrix({
       origins: origins,
       destinations: [destination],
       travelMode: google.maps.TravelMode[mode],
       unitSystem: google.maps.UnitSystem.IMPERIAL,
     }, function(response, status) {
       if (status !== google.maps.DistanceMatrixStatus.OK) {
         window.alert('Error was: ' + status);
       } else {
         displayMarkersWithinTime(response);
       }
     });
    }
   }
  
   function displayMarkersWithinTime(response){
    var maxDuration = document.getElementById('max-duration').value;
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var atLeastOne = false; 
    for (var i = 0; i &lt; origins.length; i++) {
     var results = response.rows[i].elements;
      for (var j = 0; j &lt; results.length; j++) {
       var element = results[j];
       if (element.status === "OK") {
        var distanceText = element.distance.text;
        var duration = element.duration.value / 60;
        var durationText = element.duration.text;
        if (duration &lt;= maxDuration) {
          markers[i].setMap(map);
          atLeastOne = true;
          var infowindow = new google.maps.InfoWindow({
            content : durationText + ' away, ' + distanceText + '&lt;div&gt;&lt;input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections(&amp;quot;' + origins[i] + '&amp;quot;);\"&lt;/input&gt;&lt;/div&gt;'
          });
          infowindow.open(map, markers[i]);
          // if user clicks on marker close the small info window to open a new
          markers[i].infowindow = infowindow;
          google.maps.event.addListener(markers[i], 'click', function (){
            this.infowindow.close();
          });
        }
      }
    }
   }
   if(!atLeastOne) {
     window.alert('We could not find any locations within that distance');
   }
   console.log("hello") 
   } 
  }
  
  var map;
  var markers = [];
  map = new google.maps.Map(document.getElementById('map'), {
   center: {lat: 39.9523789, lng: -75.1635996},
   zoom: 13,
   mapTypeControl: false
  });   
  
  function hideMarkers(markers) {
   for (var i = 0; i &lt; markers.length; i++){
    markers[i].setMap(null);
   }
  }
  
   function displayDirections(origin) {
    hideMarkers(markers);
    var directionsService = new google.maps.DirectionsService;
    var destinationAddress = document.getElementById('search-within-time-text').value;
    var mode = document.getElementById('mode').value;
    directionsService.route({
     origin: origin,
     destination: destinationAddress,
     travelMode: google.maps.TravelMode[mode]
    }, function(response, status) {
    console.log(response)
    console.log(status)
    if (status === google.maps.DirectionsStatus.OK) {
      var directionsDisplay = new google.maps.DirectionsRenderer({
        map: map,
        directions: response,
        draggable: true,
        polylineOptions: {
          strokeColor: 'black'
        }
       }, console.log(map), console.log(response));
      } else {
       window.alert('Directions request failed due to ' + status);
      }
     });
     console.log("testing")
    }
   google.maps.event.addDomListener(window, initMap())
  </code></pre>