Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 geolocation

I would like to get the geolocation (longitude and latitude) on loading my angular 2 app, and set it to a variable, location. How do I do this? Here is the app.component:

import { Component, OnInit} from '@angular/core';
@Component({
     moduleId: module.id,
     selector: 'app-root',
     template: `
     <h2>{{location.latitude}}</h2>
     `
     })

export class AppComponent implements OnInit{
   location = {};
   setPosition(position){
      this.location = position.coords;
      console.log(position.coords);
      }
ngOnInit(){
   if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition(this.setPosition);
      };
   }
 }

When I print position.coords, it comes out. But it does not seem to be setting this.location. Thank you.

like image 462
Noah Roston Avatar asked Jul 14 '16 01:07

Noah Roston


1 Answers

I assume you are inferring it is not setting this.location because your UI is not updated. Let confirm if this.location is being set by adding another console log in setPosition.

  console.log(this.location);

I think it would be set but UI is not updating is your issue. Just for starter you can try wrapping the location set in timeout and see if UI updates like

setTimeout( position => this.location = position.coords, 0);

If this gets you working then your a setting the variable too early/too late for change detection to pick up. You should move your code of setPosition from ngOnInit to a better lifecycle hook like 'ngAfterViewChecked' or 'ngDoCheck' but this function will be called multiple times so you do your work only once by setting proper

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

Bing will return a bound function where context would be fixed to this passed as argument

like image 85
Arpit Agarwal Avatar answered Oct 07 '22 00:10

Arpit Agarwal