4

我正在尝试在我的网站上使用的地图上使用方向,但是有一个错误不断弹出,我不知道如何摆脱它!

未捕获的 ReferenceError:未定义方向服务

这是我使用的代码

$(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!");
    }
  });
}
4

1 回答 1

11

删除此行中的 var 关键字:

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

当您使用 var 关键字时,该变量directionsService仅在函数内部可见,但您需要一个全局变量(从任何范围可见)

于 2012-10-25T11:18:03.523 回答