如何在Ionic 4的每个页面中使用地理位置

Aas*_*rty -1 ionic-framework angular

我正在使用ionic中的GeoLocation NativeGeoCoder插件进行获取。我想在多个页面中使用位置。

我在创建函数 app.component.ts

constructor(
    private geolocation: Geolocation,
    private nativegeocoder: NativeGeocoder
  ) {
    this.getGeoLocation();
  }

getGeoLocation() {
    const options: NativeGeocoderOptions = {
        useLocale: true,
        maxResults: 5
    };
    this.geolocation.getCurrentPosition().then((resp) => {
        console.log(resp);
        this.nativegeocoder.reverseGeocode(resp.coords.latitude, resp.coords.longitude, options)
        .then((result: NativeGeocoderResult[]) => {
            console.log(JSON.stringify(result[0]));
        }).catch((error) => console.log(error));
    }).catch((error) => {
        console.log(error);
    });
}

Run Code Online (Sandbox Code Playgroud)

如何使用和调用functio刷新位置。

小智 5

您必须使用watchPosition 而不是getCurrentPosition

请创建以下服务,此服务具有一项功能和一个主题,无论我们订阅了哪个主题,都可以通过该应用发出更新后的位置值。

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()

export class Location {
  private _Location = new Subject<any>();

  getGeoLocation() {
    this.geolocation.watchPosition().subscribe((position) => {
      this._Location.next(position)
      console.log(position);
    }, (err) => {
      console.log(err);
    });
  }
}    
Run Code Online (Sandbox Code Playgroud)

在组件ts文件中,您必须将服务注入到构造函数中。然后,您可以使用getGeoLocation函数更新位置,并使用_Location订阅更新的位置。

constructor(private locate: Location){}

ngOnInit() {
  // below code to take the updated snapshot of location
  this.locate.getGeoLocation()

  // below code to subscribe the updated location
  this.locate._Location.subscribe(location => {
    console.log(location);
  })
}
Run Code Online (Sandbox Code Playgroud)