1

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
  }
Noob
  • 710
  • 11
  • 15
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andreas Oct 13 '18 at 13:08

1 Answers1

0

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

Niladri
  • 5,832
  • 2
  • 23
  • 41