Google maps API - Uncaught ReferenceError: directionsService is not defined

10,441

Remove the var-keyword in this line:

var directionsService = new google.maps.DirectionsService();

When you use the var-keyword, the variable directionsService is only visible inside the function, but you need a global variable(visible from any scope)

Share:
10,441

Related videos on Youtube

Shaun Brown
Author by

Shaun Brown

A back-end PHP developer (occasional front-end work) with 2 years experience. I use Codeigniter, Drupal, Wordpress, Symfony and my own custom framework. Starting to use a lot more platforms over time. Dabbles in jQuery, Javascript and occasionaly in HTML and CSS, to the hatred of my boss for my messy code. Regular attendee of PHPNE Lover of games, drums, music...and Foo Fighters.

Updated on July 26, 2022

Comments

  • Shaun Brown
    Shaun Brown almost 2 years

    I am trying to use direction on my map used on my site, but there is one error that keeps popping up and I have no idea how to get rid of it!

    Uncaught ReferenceError: directionsService is not defined

    This is my code used

    $(window).load(function () {
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;
    });
    $(window).load(function () {
            initialize();
        });
    
    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var chicago = new google.maps.LatLng(41.850033, -87.6500523);
      var mapOptions = {
        zoom:7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: chicago
      }
      map = new google.maps.Map(document.getElementById("map"), mapOptions);
      directionsDisplay.setMap(map);
      directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    }
    
    function calcRoute() {
      var start = new google.maps.LatLng(54.986136, -1.537945);
      var end = new google.maps.LatLng(41.850033, -87.6500523);
    
      var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING
      };
      console.log(request);
      if (request==true)
      {
        console.log("REQUEST");
      }
      console.log(JSON.stringify(request)); 
      directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            if (!response.routes[0].copyrights) { 
            response.routes[0].copyrights = "Copyrights unknown."; 
            }
            console.log("ALL GOOD!");
          directionsDisplay.setDirections(result);
        }
        else
        {
            console.log("NOT-GOOD!");
        }
      });
    }