DEV Community

Juraj Chovan
Juraj Chovan

Posted on

Ako v Ionic (ver.5) pridať funkciu zistenia vlastnej polohy (geolokácia) (elegantnejšie)

V predchádzajúcom článku je popísanie implementácie geolokačného pluginu Cordova do Ionic (ver.5) aplikácie.
Teraz popíšem malú úpravu - presunutie tejto funkcionality z konkrétnej stránky do servisu. Výhodou je samozrejme to, že ak potrebujeme zisťovať GPS polohu cez tento Cordova plugin z viacerých stránok aplikácie, nie je potrebné opakovať tento kód v každej z týchto stránok, ale iba urobiť volanie funkcie zo servisu.
Inštalácia knižníc a plugin-ov je rovnaká (ak to ešte nemáme v aplikácii, projekte nainštalované) ako je popísané v predchádzajúcom článku.
Takisto je potrebné, rovnako - doplniť potrebnú referenciu a provider aj do súboru "app.module.ts".
Zmena prichádza až v tomto bode.

Ak už mám vytvorený v aplikácii nejaký servis použijem ho (ak nie vytvorím si servis nový, viď napr.článok).
V súbore tohto servisu doplniť nasledujúci kód:

    ...
import { Geolocation } from '@ionic-native/geolocation/ngx';
    locationCordinates = Array();
        ...
  constructor(
    ...
    private geolocation: Geolocation
  ) { }
  // zisti aktualnu polohu (pomocou cordova geolocation pluginu):
  async getUserCoordinates() {
    await this.geolocation.getCurrentPosition().then(
      (resp) => {
        // naplni pole hodnot, ktore bude odovzdavat naspat:
        this.locationCordinates.push(resp.coords['latitude']);
        this.locationCordinates.push(resp.coords['longitude']);
      }
    ).catch(
      (error) => {
        console.log('Error getting location', error);
      }
    );
    return this.locationCordinates;
  }
        ...
Enter fullscreen mode Exit fullscreen mode

a na stránke, kde chceme využiť túto funkcionalitu, napr.na stránke "home", tj.v súbore "home.page.ts" je potrebné doplniť:

    ...
import { PozadovanyService } from 'src/app/services/weather.service';
        ...
export class HomePage implements OnInit {
  locationCordinates: any;
  latCoords: number = 48.659052;  // default-na hodnota GPS latitude: Bohdanovce 369
  lngCoords: number = 21.399222;  // default-na hodnota GPS longitude: Bohdanovce 369
  pageContent = null;
        ...
  constructor(
    private weatherService: WeatherService,
  ) {}
  // inicializacia stranky:
  ngOnInit()  {
    this.getLocation();
  }
  // tlacitko [Get location] - zisti aktualnu polohu pouzivatela (cez servis):
  getLocation() {
    this.locationCordinates = this.weatherService.getUserCoordinates().then(
      (result) => {
        // console.log('getLocation: result: '+result);
        this.latCoords = result[0];
        this.lngCoords = result[1];
        console.log('getLocation: lat/lng: '+this.latCoords+'/'+this.lngCoords);
      }
    ).catch(
      (error) => {
        console.log('Error getting location', error);
      }
    );
  }
        ...

Enter fullscreen mode Exit fullscreen mode

Funkcionalita je vykonaná s načítaním (inicializáciou stránky), ale tiež je možné túto funkciu "getLocation()" volať aj pri stisnutí tlačítka na stránke (tj."home.page.html" mám niekde definované tlačítko):

    ...
<ion-button color="primary" shape="round" (click)="getLocation()">Get location</ion-button>

Enter fullscreen mode Exit fullscreen mode

...

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay