简体   繁体   中英

How to use Geo Location in every page in Ionic 4

I am using GeoLocation NativeGeoCoder plugins in ionic for the getting. i want to use location in multiple pages.

i am creating function in 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);
    });
}

how to use and call functio for refresh the location.

You have to use watchPosition instead of getCurrentPosition

Please create service as given below this service has one function and one subject to emit the updated location value through the app wherever we have subscribe that subject.

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);
    });
  }
}    

In component ts file You have to inject the service into constructor. and after that you can use getGeoLocation function to update the location and _Location to subscribe the updated 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);
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM