1

I am still pretty new to Angular 2 and cant get around this problem.

I am trying to get the users current location and safe his coordinates in a variable called "location". When trying to accomplish this I recieve the following error message: enter image description here

The code looks like this:

import { Component, AfterViewInit } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { AgmCoreModule } from 'angular2-google-maps/core';


@Component({
selector: 'app-home',
templateUrl: './app.home.html',
styleUrls: ['./app.home.css']
})
export class HomeAppComponent {
  //restaurants: FirebaseListObservable<any[]>;
  zoom: number = 8;
  lat: number;
  lng: number;
  location: any = {};

  constructor(private af: AngularFire) {
     //this.restaurants = af.database.list('/restaurants');
  }

  ngAfterViewInit() {
     if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(this.setPosition);
     }
  }

  setPosition(position) {
     this.location = position.coords;
     console.log(position.coords);
  }

}

When setting propery location to something like:

location.lat = 32;
location.lng = 53;

It is possible to output their values in the constructor, but in the setPosition function its null.

What am I doing wrong....

kevj
  • 55
  • 1
  • 8

2 Answers2

5

You can call using arrow function like so:

navigator.geolocation.getCurrentPosition((pos)=>this.setPosition(pos))

or if it does not send a parameter,

navigator.geolocation.getCurrentPosition(()=>this.setPosition())
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
2

navigator.geolocation.getCurrentPosition(this.setPosition)

should be

navigator.geolocation.getCurrentPosition(this.setPosition.bind(this))

Your this is not refering to the page inside setPosition

eko
  • 39,722
  • 10
  • 72
  • 98
  • Thank you very much...working with this confuses me from time to time – kevj Jan 20 '17 at 10:53
  • @kevj no problem. I suggest you to take a look at this great post :-) http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback/20279485#20279485 – eko Jan 20 '17 at 10:58