如何在多个离子4页中使用地理定位服务?

问题描述 投票:0回答:2

我已经构建了一个地理位置服务,希望在home.page上使用getUserPosition()方法

location.service.ts

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.page中访问该服务

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>

但是当我在HTML上单击(click)=“ getUserPosition()”时,出现错误getUserPosition()不是函数。我一直在网上寻找答案,但是所有答案都涉及使用home.ts文件中的地理位置。任何帮助将不胜感激。

geolocation cordova-plugins ionic4
2个回答
0
投票

根据我在home.ts中看到的内容,您尚未定义名为getUserPosition的函数。

将以下内容添加到home.ts

getUserPosition() {

  this.LocationService.getUserPosition().then((pos) => {

    this.getPosition = pos;

  });

}

0
投票

您可以像这样直接在html中调用您的服务方法

在home.ts中定义服务对象

constructor(public ls:LocationService){}

At home.html

<ion-button expand="full" color="primary" (click)="ls.getUserPosition()">
Get Location Sevice
</ion-button>

© www.soinside.com 2019 - 2024. All rights reserved.