|
| 1 | +import { Component, OnInit, OnDestroy } from '@angular/core'; |
| 2 | +import { Platform, ViewController } from 'ionic-angular'; |
| 3 | +import { Geolocation } from '@ionic-native/geolocation'; |
| 4 | +import { Location } from 'api/models'; |
| 5 | +import { Observable, Subscription } from 'rxjs'; |
| 6 | + |
| 7 | +const DEFAULT_ZOOM = 8; |
| 8 | +const EQUATOR = 40075004; |
| 9 | +const DEFAULT_LAT = 51.678418; |
| 10 | +const DEFAULT_LNG = 7.809007; |
| 11 | +const LOCATION_REFRESH_INTERVAL = 500; |
| 12 | + |
| 13 | +@Component({ |
| 14 | + selector: 'location-message', |
| 15 | + templateUrl: 'location-message.html' |
| 16 | +}) |
| 17 | +export class NewLocationMessageComponent implements OnInit, OnDestroy { |
| 18 | + lat: number = DEFAULT_LAT; |
| 19 | + lng: number = DEFAULT_LNG; |
| 20 | + zoom: number = DEFAULT_ZOOM; |
| 21 | + accuracy: number = -1; |
| 22 | + intervalObs: Subscription; |
| 23 | + |
| 24 | + constructor(private platform: Platform, |
| 25 | + private viewCtrl: ViewController, |
| 26 | + private geolocation: Geolocation) { |
| 27 | + } |
| 28 | + |
| 29 | + ngOnInit() { |
| 30 | + // Refresh location at a specific refresh rate |
| 31 | + this.intervalObs = this.reloadLocation() |
| 32 | + .flatMapTo(Observable |
| 33 | + .interval(LOCATION_REFRESH_INTERVAL) |
| 34 | + .timeInterval()) |
| 35 | + .subscribe(() => { |
| 36 | + this.reloadLocation(); |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + ngOnDestroy() { |
| 41 | + // Dispose subscription |
| 42 | + if (this.intervalObs) { |
| 43 | + this.intervalObs.unsubscribe(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + calculateZoomByAccureacy(accuracy: number): number { |
| 48 | + // Source: http://stackoverflow.com/a/25143326 |
| 49 | + const deviceHeight = this.platform.height(); |
| 50 | + const deviceWidth = this.platform.width(); |
| 51 | + const screenSize = Math.min(deviceWidth, deviceHeight); |
| 52 | + const requiredMpp = accuracy / screenSize; |
| 53 | + |
| 54 | + return ((Math.log(EQUATOR / (256 * requiredMpp))) / Math.log(2)) + 1; |
| 55 | + } |
| 56 | + |
| 57 | + reloadLocation() { |
| 58 | + return Observable.fromPromise(this.geolocation.getCurrentPosition().then((position) => { |
| 59 | + if (this.lat && this.lng) { |
| 60 | + // Update view-models to represent the current geo-location |
| 61 | + this.accuracy = position.coords.accuracy; |
| 62 | + this.lat = position.coords.latitude; |
| 63 | + this.lng = position.coords.longitude; |
| 64 | + this.zoom = this.calculateZoomByAccureacy(this.accuracy); |
| 65 | + } |
| 66 | + })); |
| 67 | + } |
| 68 | + |
| 69 | + sendLocation() { |
| 70 | + this.viewCtrl.dismiss(<Location>{ |
| 71 | + lat: this.lat, |
| 72 | + lng: this.lng, |
| 73 | + zoom: this.zoom |
| 74 | + }); |
| 75 | + } |
| 76 | +} |
0 commit comments