Navigation

Monday 15 March 2021

Ionic Capacitor: Get Current Position and Display Driving Route Using Google Maps and Geolocation.




STEP 1: The first step is to generate your YOUR_API_KEY through Google Cloud Platform by creating a new Project.

 environment.ts


export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "AIzaSyXXXXX_YOUR_API_KEY_XXXX3naZGQ",
    //authDomain: "",
    //databaseURL: "",
    projectId: "ionic6xxxfcm",
    storageBucket: "ionicxxxxfcm.appspot.com",
    messagingSenderId: "104xxxxx95283",
    appId: "1:10444xxxx52xx:android:0617e36cc3e7c8b64c0ce6"
  }
};


 STEP 2: Copy and paste the below code and import the required page.

 app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModuleIonicRouteStrategy } from '@ionic/angular';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
/* Firebase services */
import { AngularFireModule } from "@angular/fire";
import { environment } from '../environments/environment';


@NgModule({
  declarations: [
    AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
  ],
  providers: [
    { provide: RouteReuseStrategyuseClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}


 STEP 3: Copy and paste the below code to your index.html file. For more details please click here

<script src="https://maps.googleapis.com/maps/api/js?key="AIzaSyXXXXX_YOUR_API_KEY_XXXX3naZGQ"">
</script>

 index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Ionic App</title>

  <base href="/" />

  <meta name="color-scheme" content="light dark" />
  <meta name="viewport" content="viewport-fit=cover, width=device-width, 
initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="msapplication-tap-highlight" content="no" />

  <link rel="icon" type="image/png" href="assets/icon/favicon.png" />

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" /> 
</head>

<body>
  <app-root></app-root>
    <script src="https://maps.googleapis.com/maps/api/js?key="AIzaSyXXXXX_YOUR_API_KEY_XXXX3naZGQ"">
</script>
</body>

</html>



SPEP  4: Copy and paste the below code to your home.page.html.

 home.page.html 

<ion-header [translucent]="true">
  <ion-toolbar color='primary'>
    <ion-title>
      Google Map
    </ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>    
  <div #map id="map"></div>
</ion-content>



STEP 5:  Below CSS help to view the map. 

 home.page.scss 

#map{
  width100%;
  height500px;
}

STEP 6: Following codes help to initialize the map and get the current location to show the direction of the destination.

 home.page.ts 

import { ComponentElementRefViewChild } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestoreAngularFirestoreCollection } from '@angular/fire/firestore'
import { Geolocationfrom '@capacitor/core';
import { Observable } from 'rxjs';
declare var google;
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  // location: Observable<any>;
  // locationCollection: AngularFirestoreCollection<any>;
  // user = null;

  @ViewChild('map'mapElementElementRef;
  public mapany;
  public startany = "Varanasi";
  public endany = "New Delhi";
  public latitudeany;
  public longitudeany;

   public directionsService = new google.maps.DirectionsService;
   public directionsDisplay = new google.maps.DirectionsRenderer;  

  initMap() {  
    let latLng = new google.maps.LatLng(this.latitudethis.longitude);
    let mapOptions = {
          center: latLng,
          zoom: 5,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    this.map = new google.maps.Map(this.mapElement.nativeElement,mapOptions);
    this.directionsDisplay.setMap(this.map);
    this.calculateAndDisplayRoute();
    debugger;
  }

  constructor(private afAuthAngularFireAuthprivate afsAngularFirestore) {
    debugger;   
    //this.anonoLog()
    this.getLocation();
  }

  // anonoLog() {
  //   this.afAuth.signInAnonymously()
  //   .then(user => {
  //     console.log(user);
  //     debugger;
  //     this.user = user;
  //     this.locationCollection = this.afs.collection(
  //       `locations/${this.user.uid}/track`, ref => ref.orderBy('timestap')
  //     );
  //   }).catch(error => {
  //     debugger;
  //     let err = error;
  //     debugger
  //   });
  // }

  calculateAndDisplayRoute() {    
    this.directionsService.route({
      origin: this.start,
      destination: this.end,
      travelMode: 'DRIVING'
    }, (responsestatus=> {
      debugger;
      if (status === 'OK') {
        this.directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });    
  }
  async getLocation() {
    debugger;
    const position = await Geolocation.getCurrentPosition();
    debugger;
    this.latitude = position.coords.latitude;
    this.longitude = position.coords.longitude;
    console.log(position);
    this.initMap();
  }
}


 

No comments:

Post a Comment