Skip to content

Instantly share code, notes, and snippets.

@ackuser
Created November 26, 2017 17:37
Show Gist options
  • Select an option

  • Save ackuser/fadcc73c7137e3e731b2dc5a98894add to your computer and use it in GitHub Desktop.

Select an option

Save ackuser/fadcc73c7137e3e731b2dc5a98894add to your computer and use it in GitHub Desktop.
export class Coordinates {
latitude: string | number;
longitude: string | number;
accuracy?: number;
constructor(that?: Coordinates) {
if (that) {
this.latitude = +that.latitude;
this.longitude = +that.longitude;
this.accuracy = +that.accuracy;
}
}
}
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Coordinates} from './models/coordinates.model';
const GEOLOCATION_ERRORS = [
'Browser does not support location services',
'You have rejected access to your location',
'Unable to determine your location',
'Service timeout has been reached'
];
@Injectable()
export class GeolocationService {
public getLocation(): Observable<Coordinates> {
return Observable.create(observer => {
if (window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
(position) => {
observer.next(new Coordinates({
latitude: position.coords.latitude.toString(),
longitude: position.coords.longitude.toString(),
accuracy: position.coords.accuracy
}));
observer.complete();
},
(error) => observer.error(GEOLOCATION_ERRORS[+error.code]));
} else {
observer.error(GEOLOCATION_ERRORS[0]);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment