JavaScript Objects - Object values getting undefin

2019-09-04 11:36发布

I am trying to create an object that handles Google Maps Api as following:

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;
}

and the drawDirectionDriving function is like this:

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...");
      }
    }
  );
}

and in somewhere, I am using the object like this:

var myGoogleMap;

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

The Google Map is shown on my browser, there is no problem in constructing the object but error in DrawDirectionDriving function.

When I create a breakpoint on this line: " myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");" the "DirectionRenderer" seems constructed, but after this line (after the "Draw" method) the DirectionRenderer object seems null (undefined) so it outs en error like this "couldn't get setDirections properties it is null bla bla..."

Could you please give me a hand?

Thanks in advance...

1条回答
仙女界的扛把子
2楼-- · 2019-09-04 12:03

The this keyword does point to something else in the route callback function. It's DirectionRenderer property resolves to null/undefined, and getting the setDirections property from that will cause the exception.

Use a dereferencing variable:

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...");
      }
    }
  );
}
查看更多
登录 后发表回答