simplest way to get current location in Angular 2 Google Maps (AGM Core)

Yuu picture Yuu · Mar 26, 2018 · Viewed 10.7k times · Source

This question may have a duplicate or the answer that I want has already been answered in some other questions but I'll still ask anyways.. This is a very basic question but I also want the easiest(simplest) way of how to achieve this

What I want to do is get the current Location of the device in which my app was executed.. I've seen other answers using geolocation but I can't quite understand how to implement it to AGM because I'm quite new to ionic and angular, and I was wondering if there may be a more simple way to achieve this...

Your answers will be highly appreciated

Here's my code: HTML

  <ion-header>

  <ion-navbar>
    <ion-title>viewmapings</ion-title>
    <ion-buttons end>
      <button ion-button (click)="onClose()">Close</button>
    </ion-buttons>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <agm-map 
   [latitude]="lat"
   [longitude]="lng" 
   (mapClick)="onClickLoc($event)"
   [disableDoubleClickZoom] = "true"
   [streetViewControl] = "false"
    [zoom]="15">

    <agm-marker
     [latitude]="clickedLat" 
     [longitude]="clickedLng" 
     *ngIf="selected">
     <agm-info-window>Lat: {{clickedLat}} <br> Lng: {{clickedLng}}</agm-info-window>
    </agm-marker>

  </agm-map>
</ion-content>

SCSS:

page-viewmapings {
    agm-map{
        height: 100%;
    }
}

TS:

import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController } from 'ionic-angular';


@IonicPage()
@Component({
  selector: 'page-viewmapings',
  templateUrl: 'viewmapings.html',
})
export class ViewmapingsPage {

  lat: number = 51.678418;
  lng: number = 7.809007;
  clickedLat: number;
  clickedLng: number;
  selected =  false;

  constructor(public navCtrl: NavController, public viewCtrl: ViewController) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ViewmapingsPage');
  }

  onClickLoc(event){
    this.clickedLat = event.coords.lat;
    this.clickedLng = event.coords.lng;
    this.selected = true;
  }

  onClose(){
    this.viewCtrl.dismiss()
  }

}

Answer

zolastro picture zolastro · Apr 9, 2018

I've done something similar in a project. My advice is to create a service that will be in charge of that:

geo-location.service.ts

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

@Injectable()
export class GeoLocationService {

  coordinates: any;

  constructor() { }

  public getPosition(): Observable<Position> {
    return Observable.create(
      (observer) => {
      navigator.geolocation.watchPosition((pos: Position) => {
        observer.next(pos);
      }),
      () => {
          console.log('Position is not available');
      },
      {
        enableHighAccuracy: true
      };
    });
  }
}

Then, you can easily use it anywhere in your app:

coordinates;
ngOnInit() {
    this.geoLocationService.getPosition().subscribe(
        (pos: Position) => {
            this.coordinates = {
              latitude:  +(pos.coords.latitude),
              longitude: +(pos.coords.longitude)
            };
        });
    }
}

And use it with agm:

<agm-map
          [latitude]="coordinates.latitude"
          [longitude]="coordinates.longitude"
          [zoom]="10">
</agm-map>

You can skip creating the service, but it's really useful and gives you and observable, so your location updates it changes.