Nativescript位置插件仅打开位置设置

时间:2016-07-18 09:55:41

标签: nativescript angular2-nativescript

我用nativescript和angular编写了一些Code来观察位置。

但即使我的设备上的GPS已开启,geolocation.isEnabled()也会显示 false

另外,在运行geolocation.watchLocation(..)时,我的设备只会打开位置设置。并返回错误消息:

Error: Location service is not enabled or using it is not granted.

有人知道我的应用无法使用位置的原因吗?

我的app.compoment.html:

<GridLayout columns="*,*" rows="auto,auto,auto">
    <Label text="Geolocation" class="title" row="0" colSpan="2"></Label>
    <Button row="1" col="0" text="Start Tracking" (tap)="startTracking()"></Button>
    <Button row="1" col="1" text="Stop Tracking" (tap)="stopTracking()"></Button>
    <Label row="2" col="0" text="Latitude: {{latitude}}"></Label>
    <Label row="2" col="1" text="Longitude: {{longitude}}"></Label>
</GridLayout>

我的app.component.ts:

@Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent {

latitude = "42";
longitude = "5";
watchId = 0;

public startTracking() {
    console.log("Start Tracking");

    /* Check if GPS is enabled. */
    if (geolocation.isEnabled()) {
        console.log("GPS is enabled.");
    } else {
        console.log("GPS is disabled.");
    }

    /* Get Location */
    this.watchId = geolocation.watchLocation(function (loc) {
            if (loc) {
                console.log("Current location is: " + loc);
            }
        }, function (e) {
            console.log("Error: " + e.message);
        },
        {desiredAccuracy: enums.Accuracy.any, updateDistance: 10, minimumUpdateTime: 1000});
}

public stopTracking() {
    console.log("Stop Tracking");
    if (this.watchId) {
        geolocation.clearWatch(this.watchId);
        this.watchId = 0;
    }
}
}

1 个答案:

答案 0 :(得分:1)

您是否尝试在设备上明确设置地理定位服务的权限?

public enableLocationTap() { 
    if (!geolocation.isEnabled()) {
        geolocation.enableLocationRequest();
    }
}

// in page.html
<StackLayout>
    <Button text="enable Location" (tap)="enableLocationTap()"></Button>
</StackLayout>

触发按钮后,应用程序应显示允许/取消样式消息的权限弹出窗口。