0

我正在尝试创建一个处理 Google Maps Api 的对象,如下所示:

function GoogleMap(container, mapOptions) {
    this.Container = container;
    this.Options = mapOptions;
    this.Map = new google.maps.Map(document.getElementById(this.Container), this.Options);

    // Direction
    this.DirectionService = new google.maps.DirectionsService();
    this.DirectionRenderer = new google.maps.DirectionsRenderer();
    this.DirectionRenderer.setMap(this.Map);
    this.DirectionId = 0;
    this.DirectionResponse = new Array();
    this.DrawDirectionDriving = drawDirectionDriving;
}

drawDirectionDriving 函数是这样的:

function drawDirectionDriving(start, end) {
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
  };

  this.DirectionService.route(request,
    function (response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        this.DirectionRenderer.setDirections(response);
        this.DirectionResponse[this.DirectionId] = response;
        this.DirectionId++;
      }
      else {
        alert("Error during drawing direction, Google is not responding...");
      }
    }
  );
}

在某个地方,我正在使用这样的对象:

var myGoogleMap;

function MapInit() {
    myGoogleMap = new GoogleMap("divMap", myMapOptions);
    myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");
}

谷歌地图显示在我的浏览器上,构造对象没有问题,但 DrawDirectionDriving 函数出错。

当我在这一行创建断点时:“myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");" “DirectionRenderer”似乎已构建,但在此行之后(在“Draw”方法之后)DirectionRenderer 对象似乎为空(未定义),因此它会出现这样的错误“无法获取 setDirections 属性,它为空 bla bla ...”

你能帮我一把吗?

提前致谢...

4

1 回答 1

2

this关键字确实指向route回调函数中的其他内容。它的DirectionRenderer属性解析为null/ undefined,从中获取setDirections属性将导致异常。

使用解引用变量:

function drawDirectionDriving(start, end) {
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
  };
  var that = this;

  this.DirectionService.route(request,
    function (response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        that.DirectionRenderer.setDirections(response);
        that.DirectionResponse[this.DirectionId] = response;
        that.DirectionId++;
//      ^^^^ points to the GoogleMap instance
      }
      else {
        alert("Error during drawing direction, Google is not responding...");
      }
    }
  );
}
于 2012-08-06T22:12:28.193 回答