Geolocation 如何在多个4页中使用地理定位服务?
我已经构建了一个地理位置服务,我希望在home.page上使用getUserPosition()方法 location.service.tsGeolocation 如何在多个4页中使用地理定位服务?,geolocation,cordova-plugins,ionic4,Geolocation,Cordova Plugins,Ionic4,我已经构建了一个地理位置服务,我希望在home.page上使用getUserPosition()方法 location.service.ts import { Injectable } from '@angular/core'; import { Geolocation, GeolocationOptions, Geoposition, PositionError } from '@ionic-native/geolocation/ngx'; @Injectable({ providedI
import { Injectable } from '@angular/core';
import { Geolocation, GeolocationOptions, Geoposition, PositionError } from '@ionic-native/geolocation/ngx';
@Injectable({
providedIn: 'root'
})
export class LocationService {
options: GeolocationOptions;
currentPos: Geoposition;
loc: any;
constructor( private geolocation: Geolocation ) { }
getUserPosition() {
return new Promise((resolve, reject) => {
this.options = {
maximumAge: 3000,
enableHighAccuracy: true
};
this.geolocation.getCurrentPosition(this.options).then((pos: Geoposition) => {
this.currentPos = pos;
const location = {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
time: new Date(),
};
console.log('loc', location);
resolve(pos);
}, (err: PositionError) => {
console.log("error : " + err.message);
reject(err.message);
});
});
}
}
我在我的主页上访问该服务
home.ts
import { Component, OnInit } from '@angular/core';
import { LocationService } from '../../services/geolocation/location.service';
@Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class WorkalonePage implements OnInit {
getPosition: any;
constructor(
private LocationService: LocationService
) {}
ngOnInit() {
this.getPosition = this.LocationService.getUserPosition;
}
}
home.html
<ion-content>
<ion-button expand="full" color="primary" (click)="getUserPosition()">Get Location Sevice</ion-button>
</ion-content>
<ion-button expand="full" color="primary" (click)="ls.getUserPosition()">
Get Location Sevice
</ion-button>
获取定位服务
但是当我在html上单击(click)=“getUserPosition()”时,我得到的错误是getUserPosition()不是函数。我一直在网上寻找答案,但所有答案都涉及使用home.ts文件中的地理位置。任何帮助都将不胜感激 从我在
home.ts
中看到的,您还没有定义名为getUserPosition
的函数
在home.ts中添加以下内容:
getUserPosition() {
this.LocationService.getUserPosition().then((pos) => {
this.getPosition = pos;
});
}
您可以像这样在html中直接调用您的服务方法
位置服务
getUserPosition() {
this.LocationService.getUserPosition().then((pos) => {
this.getPosition = pos;
});
}
在home.ts中定义服务对象
constructor(public ls:LocationService){}
home.html
<ion-button expand="full" color="primary" (click)="ls.getUserPosition()">
Get Location Sevice
</ion-button>
获取定位服务