在 Ionic 2 中实施地理定位跟踪时出错
Posted
技术标签:
【中文标题】在 Ionic 2 中实施地理定位跟踪时出错【英文标题】:Error on implementing geolocation tracking in Ionic 2 【发布时间】:2017-11-26 11:34:06 【问题描述】:我正在尝试在我的新项目中实施地理定位。我已经安装了以下插件并将它们添加到app.module.ts
ionic cordova plugin add cordova-plugin-mauron85-background-geolocation
npm install --save @ionic-native/background-geolocation
我正在关注this tutorial,但在home.ts
中出现错误。下面是我的home.ts
代码。
import Component from '@angular/core';
import NavController from 'ionic-angular';
import BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse from '@ionic-native/background-geolocation';
@Component(
selector: 'page-home',
templateUrl: 'home.html'
)
export class HomePage
constructor(private backgroundGeolocation: BackgroundGeolocation,public navCtrl: NavController)
const config: BackgroundGeolocationConfig =
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
debug: true, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false, // enable this to clear background location settings when the app terminates
;
this.backgroundGeolocation.configure(config)
.subscribe((location: BackgroundGeolocationResponse) =>
console.log(location);
// IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished,
// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
//this.backgroundGeolocation.finish(); // FOR IOS ONLY
);
// start recording location
this.backgroundGeolocation.start();
// If you wish to turn OFF background-tracking, call the #stop method.
this.backgroundGeolocation.stop();
错误出现在这一行:this.backgroundGeolocation.configure(config)
。在this
上面写着;
[ts] 意外标记。需要构造函数、方法、访问器或属性。
在配置上它说:
[ts] 找不到名称“配置”
【问题讨论】:
你是在构造函数外调用this.backgroundGeolocation.configure(config)
吗?
这也是文档中的代码 sn-p.. 不是教程链接
【参考方案1】:
正如@SurajRao 在他的评论中指出的那样,您需要将代码移动到类构造函数中或将其包装在方法中。
这是您的组件,代码放置在构造函数中:
import Component from '@angular/core';
import NavController from 'ionic-angular';
import BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse from '@ionic-native/background-geolocation';
@Component(
selector: 'page-home',
templateUrl: 'home.html'
)
export class HomePage
constructor(private backgroundGeolocation: BackgroundGeolocation,public navCtrl: NavController)
const config: BackgroundGeolocationConfig =
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
debug: true,
stopOnTerminate: false,
;
this.backgroundGeolocation.configure(config)
.subscribe((location: BackgroundGeolocationResponse) =>
console.log(location);
);
this.backgroundGeolocation.start();
this.backgroundGeolocation.stop();
阅读更多关于javascript classes on MDN的信息。
【讨论】:
以上是关于在 Ionic 2 中实施地理定位跟踪时出错的主要内容,如果未能解决你的问题,请参考以下文章
cordova-ionic 应用程序在后台进行地理定位 - android 和 ios