Find Near By Location In Ionic 3 Using Google Map API

Ionic 3 Using Google Map API

 

Google nearby location:-

Maps are always needed for finding the nearby places for our daily routine work. Here is the simple example how we can use the google map API in ionic 3 application for finding the nearby places like: hospital, restaurant, bank, airport, library, gym, etc.

 

Google Maps API will be used to display the maps. There are lot of things you can do with the maps API like find the nearby places, get the direction between two places etc. We will explore how to apply place recommendations and suggestions using Google Places API.

 

Steps:-

First, install the google map library using this.
 

npm install @types/googlemaps --save-dev

Now go to node_modules and then @types and inside that Google maps folder and add below line

declare module 'googlemaps';

Now we will use the google map js library for getting informed about the places. So include the Google Map js file in the index.html file.

 

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

The above script needs the google map API key. Follow these steps:-

  • Go to https://console.developers.google.com
  • Create a new Google project and give appropriate name to your project
  • Once you created a new project, it will redirect you to the API section and click the google maps Javascript API
  • Click the enable API. Then click the create credentials and click the what credentials do I need?
  • That's all. It will give you the google map API key

Then install geolocation plugin in order to access the user location.

 

$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install --save @ionic-native/geolocation

Now to import geolocation plugin in app.module.ts file.

 

import { Geolocation } from '@ionic-native/geolocation';      
@NgModule({    
     ...   
     providers: [  Geolocation   ]  
     ... })

 

Then import the Google maps class and geolocation plugin to the home.ts file.

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

import { googlemaps } from 'googlemaps';

 

Now use the google map places API like this.

 let service = new google.maps.places.PlacesService(this.map);

Now add this code to your home.ts file.

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  @ViewChild('map') mapElement: ElementRef;

  map:any;
  latLng:any;
  markers:any;
  mapOptions:any;  
  isKM:any=500;
  isType:any="";
 
  constructor(private ngZone: NgZone, private geolocation : Geolocation) { }

  ionViewDidLoad() {
    this.loadMap();
  }

  loadMap(){

    this.geolocation.getCurrentPosition().then((position) => {

this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

          console.log('latLng',this.latLng);
     
      this.mapOptions = {
        center: this.latLng,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }   

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

    }, (err) => {
      alert('err '+err);
    });

  }


 /*--------------------Find Nearby Place------------------------*/ 

  nearbyPlace(){
    this.loadMap();
    this.markers = [];
    let service = new google.maps.places.PlacesService(this.map);
    service.nearbySearch({
              location: this.latLng,
              radius: this.isKM,
              types: [this.isType]
            }, (results, status) => {
                this.callback(results, status);
            });
  }

  callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        this.createMarker(results[i]);
      }
    }
  }

  createMarker(place){
    var placeLoc = place;
    console.log('placeLoc',placeLoc);
    this.markers = new google.maps.Marker({
        map: this.map,
        position: place.geometry.location
    });

    let infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(this.markers, 'click', () => {
      this.ngZone.run(() => {
        infowindow.setContent(place.name);
        infowindow.open(this.map, this.markers);
      });
    });
  }

}

 

Now Add this code to your home.html file for selecting places type and places distance find nearby places.
 

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Map
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
<ion-item>
<ion-label>Select Place</ion-label>
  <ion-select [(ngModel)]="isType" (ionChange)="nearbyPlace()">
  <ion-option value="">Select</ion-option>
      <ion-option value="hospital">Hospital</ion-option>
      <ion-option value="restaurant">Restaurant</ion-option>
      <ion-option value="bank">Bank</ion-option>
      <ion-option value="airport">Airport</ion-option>
      <ion-option value="library">Library</ion-option>
      <ion-option value="gym">Gym</ion-option>
    <ion-option value="atm">Atm</ion-option>
    <ion-option value="shopping_mall">Shopping Mall</ion-option>
    <ion-option value="police">Police Station</ion-option>
    <ion-option value="zoo">Zoo</ion-option>
  </ion-select>
</ion-item>

<ion-item>
<ion-label>Select Distance</ion-label>
  <ion-select [(ngModel)]="isKM" (ionChange)="nearbyPlace()">
  <ion-option value="500">Select</ion-option>
      <ion-option value="2000">2 KM</ion-option>
      <ion-option value="4000">4 KM</ion-option>
      <ion-option value="6000">6 KM</ion-option>
      <ion-option value="8000">8 KM</ion-option>
  </ion-select>
</ion-item>

<div #map id="map"></div>
    
</ion-content>

 

Hope this helps you well, feel free to add your comments/feedbacks. Need more assistance regarding Ionic App Development Get in touch today!