Search code examples
typescriptnavigator

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


I found mostly the kind of codes like the one below, which may work in javascript, but I can't get it to work in 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 ERROR TypeError: Cannot read property 'ShowLocation' of null

I don't know how to make this work in typescript. I don't understand why it gives that error.

edit: found the solution in the possible duplicate link, had to use bind for "this", thanks!


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

Solution

  • You need to use arrow function instead of using anonymous function as the parameter to the navigator.geolocation.getCurrentPosition method. Arrow function does not create a scope of it's own and uses the parent scope. So when you use arrow function your this in this line

    this.ShowLocation(position, this.map);
    

    point correctly to the instance of the typescript class. Your code should be like below-

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

    If you are looking for an example with Angular then here is a demo

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