Angular 2 geolocation

I would like to get geolocation (longitude and latitude) when loading my angular 2 application and set it to a variable, location. How should I do it? 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 exits. But this is not like setting this.location. Thank.

+4
source share
2 answers

I assume that you conclude that this is not the job of this.location, because your user interface is not updating. Confirm if this.location is set by adding another console log to setPosition.

  console.log(this.location);

, , , . , , , ,

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

, . setPosition ngOnInit , 'ngAfterViewChecked' 'ngDoCheck', , ,

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

Bing , , argument

+8

:

ngOnInit(){
   if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition(position => {
        this.location = position.coords;
        console.log(position.coords); 
      });
   }
 }
+4

All Articles