1

I have an application which displays postcodes from a database, when a button is clicked the postcodes are geocoded and displayed as markers on a Google map in a pop up window. I'm trying to show the driving route between the two markers on the map. I have saved the geocoded values into HTML span tags and I'm trying to use these values as the origin and destination for the route. Everything works apart from the route showing between the markers which shows an error message 'Directions request failed due to NOT_FOUND'.

Any idea how I can get the route to show up?

$(document).ready(function () {

        $(".openMap").click(function () {

            var directionsService = new google.maps.DirectionsService;
            var mapLocation = $(this).prev().prev().prev().text();
            var secondMarker =  $(this).prev().prev().text();
            window.markers = [];
            var geocoder = new google.maps.Geocoder(); 

            geocoder.geocode({ address: mapLocation }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };

                    map = new google.maps.Map(document.getElementById('map'), mapOptions);

                    var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
                    directionsDisplay.setMap(map);

                    var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Departure Location" });                                                    
                markers.push(marker);
                $('#route1').text(results[0].geometry.location);
            }

        });
        var geocoder2 = new google.maps.Geocoder(); 

            geocoder.geocode({ address: secondMarker }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    var marker2 = new google.maps.Marker({ map: map, position: results[0].geometry.location,  title: "Destination Location" }); 
                markers.push(marker2);
                $('#route2').text(results[0].geometry.location);

            var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < markers.length; i++) {
            bounds.extend(markers[i].getPosition());
        }
            map.fitBounds(bounds);  
            }
        });

             directionsService.route({
             origin: $('#route1').text(),
             destination: $('#route2').text(),
             travelMode: google.maps.TravelMode.DRIVING
            }, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            } else {
            window.alert('Directions request failed due to ' + status);
            }
        });
        $("#map").dialog({ title: "Lift Location ", height: 500, width: 500, modal: true });

                });
    });
3
  • I get an error with your code: Uncaught ReferenceError: directionsDisplay is not defined Commented Feb 27, 2016 at 0:52
  • What does your CSS/HTML look like? Please provide a Minimal, Complete, Tested and Readable example that demonstrates your issue. Commented Feb 27, 2016 at 1:10
  • jsfiddle.net/szw6yg6g Commented Feb 27, 2016 at 10:18

1 Answer 1

1

route1 and route2 are empty. The API doesn't know how to create a route from "" to "".

Once I fix that (to use post1 and post2 which contain the postcodes), I get a javascript error: Uncaught ReferenceError: directionsDisplay is not defined.

Fixing that shows me a route.

proof of concept fiddle

code snippet:

$(document).ready(function() {
  var directionsDisplay;
  $(".openMap").click(function() {

    var directionsService = new google.maps.DirectionsService;
    var mapLocation = $(this).prev().prev().prev().text();
    var secondMarker = $(this).prev().prev().text();
    window.markers = [];
    var geocoder = new google.maps.Geocoder();
    var mapOptions = {
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map'), mapOptions);

    geocoder.geocode({
      address: mapLocation
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);

        directionsDisplay = new google.maps.DirectionsRenderer({
          map: map
        });
        directionsDisplay.setMap(map);

        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: "Departure Location"
        });
        markers.push(marker);
        $('#route1').text(results[0].geometry.location);
      }

    });
    var geocoder2 = new google.maps.Geocoder();

    geocoder.geocode({
      address: secondMarker
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        var marker2 = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: "Destination Location"
        });
        markers.push(marker2);
        $('#route2').text(results[0].geometry.location);

        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < markers.length; i++) {
          bounds.extend(markers[i].getPosition());
        }
        map.fitBounds(bounds);
      }
    });
    console.log("post1:" + $('.post1').text());
    console.log("post2:" + $('.post2').text());
    directionsService.route({
      origin: $('.post1').text(),
      destination: $('.post2').text(),
      travelMode: google.maps.TravelMode.DRIVING
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        if (!directionsDisplay || !directionsDisplay.getMap || (directionsDisplay.getMap() == null)) {
          directionsDisplay = new google.maps.DirectionsRenderer({
            map: map
          });
          directionsDisplay.setMap(map);
        }
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
    $("#map").dialog({
      title: "Lift Location ",
      height: 500,
      width: 500,
      modal: true
    });
    $(".selector").dialog({
      resizeStop: function(event, ui) {
        google.maps.event.trigger(map, 'resize');
      }
    });
    $(".selector").dialog({
      open: function(event, ui) {
        google.maps.event.trigger(map, 'resize');
      }
    });

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<div id="map" style="display: none;">
</div>
<span class='post1'>G1 3SL</span>
<span class='post2'>G1 2AF</span>
<br/>
<button class='openMap'>View On Map</button>
<br/>
<span id="route1"></span>
<span id="route2"></span>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.