Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, subscribe when coordinates are received

I'm learning Angular 2. I'm using a LocationService with an Observable that hands me the coordinates after some time. This is my code.

location.service.ts

public getLocation(): Observable<any> {
    return Observable.create(observer => {
        if(window.navigator && window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition(
                (position) => {
                    observer.next(position);
                    observer.complete();
                },
                (error) => observer.error(error)
            );
        } else {
            observer.error('Unsupported Browser');
        }
    });
}

app.component.ts

ngOnInit() {
    this.location.getLocation().subscribe((coordinates) => {
        this.lat = coordinates.coords.latitude;
        this.lng = coordinates.coords.longitude;
    });
}

How can I subscribe to the receiving of the coordinates so I can render a map, add a marker, .. once I receive them from the first subscribe.

like image 571
Miguel Stevens Avatar asked Dec 19 '22 09:12

Miguel Stevens


1 Answers

Firstly, I would put that method into a service.

So say you have a file called location.service.ts with the export class LocationService inside this file you'll have the following

getLocation(): Observable<any> {
    return Observable.create(observer => {
        if(window.navigator && window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition(
                (position) => {
                    observer.next(position);
                    observer.complete();
                },
                (error) => observer.error(error)
            );
        } else {
            observer.error('Unsupported Browser');
        }
    });
}

Inside your component you'll do something like this:

import { Component, OnInit } from '@angular/core';
import { LocationService } from '/shared/location.service.ts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implments OnInit {

  constructor(private service: LocationService) {}

   ngOnInit(){
     this.service.getLocation().subscribe(rep => {
        // do something with Rep, Rep will have the data you desire.
     });
   }
}
like image 159
Code Ratchet Avatar answered Dec 30 '22 18:12

Code Ratchet