Search code examples
geolocationcordova-pluginsionic4

How do use geolocation service in multiple ionic 4 pages?


I have built a geolocation service that I wish to use the getUserPosition() method on the home.page

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

I access the service in my 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>

but when I click on (click)="getUserPosition()" on my html I get the error getUserPosition() is not a function. I have have been looking online for answers, but all answers involve using the geolocation in the home.ts file. Any help would be greatly appreciated.


Solution

  • You can directly call your service method in html like this

    LocationService.ts

    getUserPosition() {
    
      this.LocationService.getUserPosition().then((pos) => {
    
        this.getPosition = pos;
    
      });
    
    }
    
    

    Define service object in home.ts

    constructor(public ls:LocationService){}
    

    At home.html

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