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.
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.
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With