Ionic 3 - Create a Nearby Restaurants App with Geolocation Plugin ,Google Maps and Places API -- Words (972)

Ionic
Ionic 2/3 Geolocation ,Google maps and Places API

In this tutorial we are going to create a nearby restaurants mobile app using Ionic 3

Throughout this tutorial We are going to learn how to use

The Cordova Geolocation plugin and its Ionic Native wrapper to get the current user position or GPS location .

Google maps to dispaly a map with a marker showing current user position.

Google Places API to get a list of nearby places or restaurants in our case.

This tutorial has two parts :

Ionic 3 - Create a Nearby Restaurants App with Geolocation Plugin ,Google Maps and Places API

Ionic 3 - Create a Nearby Restaurants App with Geolocation Plugin ,Google Maps and Places API Part 2

Generating a new project based on Ionic 3


Lets start by generating a new Ionic project using the Ionic CLI v3 .open your terminal or command prompt and run

ionic start nearby-restaurants blank 

Navigate inside your project root directory

cd nearby-restaurants 
ionic serve 

Adding a target Android platform


Since I'm building an Android app I'm going to add an Android target but you can also add an ios or windows platform

ionic cordova platform add android 

Next run the app on your device with

ionic run android -l 

Now just continue developing your app ,all changes will be synced automatically to your mobile device thanks to -l switch

Installing and configuring the Cordova Geolocation plugin and Ionic Native wrapper


The Cordova Geolocation plugin allows you to get current user location or GPS position which is what we need to be able to get nearby restaurants so lets add the plugin by running :

ionic cordova plugin add cordova-plugin-geolocation --save 

Then install the Ionic native 3.x+ wrapper for this plugin via npm

npm install --save @ionic-native/geolocation 

Next we need to add a little bit of configuration so head over to src/app/app.module.ts then start by import Geolocation from ionic-native and add it to the list of main module providers .

@NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {}

Getting current user position with Geolocation Cordova plugin


Head over to src/pages/home/home.ts then do the following :

Start by importing Geolocation ,GeolocationOptions ,Geoposition ,PositionError

import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation'; 

Inject Geolocation via component constructor

  constructor(public navCtrl: NavController,private geolocation : Geolocation) {}

Add two members for options and current position

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
options : GeolocationOptions;
currentPos : Geoposition;
constructor(public navCtrl: NavController,private geolocation : Geolocation) {} 

Add a method getUserPosition

getUserPosition(){
    this.options = {
        enableHighAccuracy : true
    };

    this.geolocation.getCurrentPosition(this.options).then((pos : Geoposition) => {

        this.currentPos = pos;      
        console.log(pos);

    },(err : PositionError)=>{
        console.log("error : " + err.message);
    });
}

Call getUserPosition when the view did enter

ionViewDidEnter(){
    this.getUserPosition();
}    

Adding Google Maps JavaScript SDK


After getting current user position ,we need to display that position in a Google map .But we need first to setup the Google Maps JavaScript SDK .

open src/index.html then add this script tag to include the SDK

<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY_HERE"></script>

To grab an API key go to this link

After getting the API key paste it in instead of YOURAPIKEY_HERE in the script tag .

Next add two variables

import { Component , ViewChild ,ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation'; 

declare var google;

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
options : GeolocationOptions;
currentPos : Geoposition;
@ViewChild('map') mapElement: ElementRef;
map: any;

Then add this method to create a map

addMap(lat,long){

    let latLng = new google.maps.LatLng(lat, long);

    let mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    this.addMarker();

}

Then this method to add a marker

addMarker(){

    let marker = new google.maps.Marker({
    map: this.map,
    animation: google.maps.Animation.DROP,
    position: this.map.getCenter()
    });

    let content = "<p>This is your current position !</p>";          
    let infoWindow = new google.maps.InfoWindow({
    content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
    infoWindow.open(this.map, marker);
    });

}

Change your getCurrentPosition() method to display the map based on the current user position

getUserPosition(){
    this.options = {
    enableHighAccuracy : false
    };
    this.geolocation.getCurrentPosition(this.options).then((pos : Geoposition) => {

        this.currentPos = pos;     

        console.log(pos);
        this.addMap(pos.coords.latitude,pos.coords.longitude);

    },(err : PositionError)=>{
        console.log("error : " + err.message);
    ;
    })
}

Next you need to change src/pages/home/home.html

<ion-header>
<ion-navbar>
    <ion-title>
    Nearby Me Restaurants
    </ion-title>
    <ion-buttons end>
    <button ion-button (click)="showNearbyResto()"><ion-icon name="list"></ion-icon>Restaurants</button>
    </ion-buttons>  

</ion-navbar>
</ion-header>

<ion-content padding>

<div #map id="map"></div> 

</ion-content>

The map won't show up but it's there ,all you need to do is to add some styles to src/pages/home/home.scss

page-home {
    .scroll {
        height: 100%
    }

    #map {
        width: 100%;
        height: 100%;
    }
}

Conclusion


That's the end of this part ,we have seen how to get the current user position using the Cordova Geolocation plugin then how to display the user current position on a Google map .

On the next part we'll continue building our app to display a list of nearby locations (restaurants) using the Google Location API .




mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.