我正在开发一个简单的 POC 来显示当前位置。 该程序从 geolocation.watchLocation 接收信息,但是该位置不会绑定(bind)并显示在屏幕上,直到我按下“停止监控”按钮。需要注意的是,日志正确显示了坐标
JS: Start Monitoring ...
JS: Location: 49.6411839:6.0040451
JS: Stop Monitoring ...
import {Component} from "@angular/core";
import {Router} from "@angular/router";
import geolocation = require("nativescript-geolocation");
@Component({
selector: "TrackingPageSelector",
template:`
<StackLayout>
<Button [text]="watchId==0 ? 'Start Monitoring' : 'Stop Monitoring'" (tap)="buttonStartStopTap()"></Button>
<Label class="labelValue" [text]="latitude"> </Label>
<Label class="labelValue" [text]="longitude"> </Label>
</StackLayout>`
})
export class TrackingPageComponent {
latitude: number = 0;
longitude: number = 0;
watchId: number = 0;
constructor(private router: Router) {}
ngOnInit() {
if (!geolocation.isEnabled()) geolocation.enableLocationRequest();
}
public buttonStartStopTap() {
if (this.watchId != 0) {
console.log('Stop Monitoring ...');
geolocation.clearWatch(this.watchId);
this.watchId = 0;
} else {
console.log('Start Monitoring ...');
let _self = this;
this.watchId = geolocation.watchLocation(
function (loc) {
if (loc) {
_self.latitude = loc.latitude;
_self.longitude = loc.longitude;
console.log(`Location: ${_self.latitude}:${_self.longitude}`);
}
},
function(e){
this.errorMsg = e.message;
},
{desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime: 1000 * 3}); // Should update every X seconds
}
}
}
最佳答案
如果您使用 ()=>
而不是 function ()
那么您就不需要 _self
hack。
看起来您需要手动调用更改检测。 NgZone 似乎没有覆盖 geolocation.watchLocation()
constructor(private cdRef:ChangeDetectorRef) {}
...
this.watchId = geolocation.watchLocation(
(loc) => {
if (loc) {
this.latitude = loc.latitude;
this.longitude = loc.longitude;
this.cdRef.detectChanges();
console.log(`Location: ${this.latitude}:${this.longitude}`);
}
},
(e) => {
this.errorMsg = e.message;
},
或者zone.run(() => ...)
类似
constructor(private zone:NgZone) {}
...
this.watchId = geolocation.watchLocation(
(loc) => {
if (loc) {
this.zone.run(() => {
this.latitude = loc.latitude;
this.longitude = loc.longitude;
console.log(`Location: ${this.latitude}:${this.longitude}`);
});
}
},
(e) => {
this.errorMsg = e.message;
},
如果您只更改本地字段,cdRef.detectChanges()
是更好的选择,如果您调用可能修改当前组件外部某些状态的方法,zone.run(.. .)
是更好的选择。
关于binding - 具有 Angular2 数据绑定(bind)的 NativeScript 不适用于地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38500517/