如何在 typescript 的 navigator.geolocation.getCurrentPosition 的成功回调函数中传递额外的参数?

How to pass extra arguments in success callback function of navigator.geolocation.getCurrentPosition in typescript?

我发现大部分代码如下所示,可能在 javascript 中工作,但我无法在 Typescript 中工作。

//javascript version
    navigator.geolocation.getCurrentPosition( function(position){
     ShowLocation( position, variable );
}); 

  function ShowLocation(position, variable){
  console.log(position, variable);
}

//what I've tried on typescript
  map:any="test";
  
  private GetCurrentLocation(): void {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
      function (position) { 
         /*something goes wrong here*/
         this.ShowLocation(position, this.map);
      });
    } else {
      alert("Geolocation is not supported by this browser.");
    }
  }

  public ShowLocation(position: any, map: any): void {
    console.log(position, map);
    //do something with the position and map parameters
  }

core.js:1448 错误类型错误:无法读取 属性 'ShowLocation' of null

我不知道如何在打字稿中完成这项工作。我不明白为什么会出现这个错误。

编辑:在可能的重复项 link 中找到了解决方案,必须为“this”使用绑定,谢谢!


//working code
//what I've tried on typescript
  map:any="test";
         

  private GetCurrentLocation(): void {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
      function (position) {
         this.ShowLocation(position, this.map);
      }.bind(this));
    } else {
      alert("Geolocation is not supported by this browser.");
    }
  }

  public ShowLocation(position: any, map: any): void {
    console.log(position, map);
    //do something with the position and map parameters
  }

您需要使用箭头函数而不是使用匿名函数作为 navigator.geolocation.getCurrentPosition 方法的参数。箭头函数不创建它自己的作用域并使用父作用域。因此,当您在这一行

中使用箭头函数时,您的 this
this.ShowLocation(position, this.map);

正确指向打字稿的实例class。您的代码应该如下所示 -

public GetCurrentLocation(): void {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition((position)  =>            { 
             this.ShowLocation(position, this.map);
          });
        } else {
          alert("Geolocation is not supported by this browser.");
        }
      }

      private ShowLocation(position: any, map: any): void {
        console.log(position.coords.latitude);
      }

如果您正在寻找 Angular 的示例,那么这里有一个演示

https://stackblitz.com/edit/angular-google-map-vcmrfe