简体   繁体   中英

Geolocation: ERROR TypeError: Cannot set property 'lat' of null

Introduction

I'm working on an Angular application where I want to get the current position of the user and save the longtitude and altitude in two properties lng and lat , yet this doesn't seem to work and no matter what I try; I keep on getting the error ERROR TypeError: Cannot set property 'lat' of null

TypeScript code (the relevant part)

  lat : any;
  lng : any;

  constructor() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(this.setValues);
    }
   }

  setValues(values) {
    this.lat = values?.coords?.latitude
    this.lng = values?.coords?.longitude;
  }

The error is thrown in the first line of setValues

The (relevant part of the) JSON object that is returned by getCurrentPosition

{
  coords:
  {
    latitude: 27.380583,
    longitude: 33.631839
  }
}

What I tried

  • The JSON is well received and I can print it, also its subobjects. I can even bind it to a local variable within the setValues method. I also tried binding that local variable to the properties but that caused the same error.
  • Changing lat: any to lat: number or adding public in front of it.
  • Getting rid of the null operators in the setValues method.
  • Putting the code in the ngOnInit method.

All of these tries caused the same error.

The problem is to do with what this refers to in different scopes. It only refers to the outer scope (the component in this case) when you use an arrow function. Otherwise this refers to the funtion itself.

You can see it in action for yourself by setting up the following test:

ngOnInit() {

  // 1. delegate function
  this.getValues(this.setValues);

  // 2. function() { }
  this.getValues(function(values) {
    console.log(this);
  });

  // 3. arrow function
  this.getValues(values => this.setValues(values));
}

getValues(callback: (values) => void) {
  callback({
    lat: 1,
    long: 2
  });
}

setValues(values) {
  console.log(this);
}

This shows 3 different ways of passing a function in as a callback. 1. and 2. will log undefined to the console. 3. will log the containing class ( AppComponent in my demo).

DEMO: https://stackblitz.com/edit/angular-c8eypx

I'm not 100% sure what the problem is, but it has to do with the scope and by making an anonymous callback function it seems to work fine.


  constructor() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((values) => { 
        this.lat = values?.coords?.latitude
        this.lng = values?.coords?.longitude;
      });
    }
   }

You can make your function anonymous:

  setValues = (values) => {
    this.lat = values?.coords?.latitude
    this.lng = values?.coords?.longitude;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM