I want to implement google places api

i want to implement google places api.How can i do that please give me a example of code or tutorial.

Hi, @flycoders_sourav

you can try this code,

index.html

<script src="http://maps.google.com/maps/api/js?key=Your Key&libraries=places"></script>

home.ts

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);
     
      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);
      });
    });
  }

}

home.html

<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>

Thanks ,

@addwebsolution Showing an error Cannot find name ‘googlemaps’.

Which kind of error could you add here

Here’s a working example with a map, a popover that acts as the searchbar and holds the places results, and a provider that does some work for both. I just started this a few days ago, so it’s a work in progress, messes with the DOM too much at this point, and has some quirks. But it works. It’s a lot of code. Let me know if it works out for you. You’ll notice some quirks, and It’d be great if you end up improving on them. If you do, let me know!

Map Component

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, ModalController, PopoverController, NavParams} from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { GoogleMaps, GoogleMap, LatLng, GoogleMapsEvent, GoogleMapOptions, CameraPosition, MarkerOptions, Marker } from '@ionic-native/google-maps';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder';
import { MapServiceProvider, geoResults } from '../../providers/map-service/map-service';
import { PopoverPageComponent } from '../../pages/popover-page/popover-page';

declare var google;

@Component({
  selector: 'page-map',
  templateUrl: 'map.html'
})
export class MapPage {

map: GoogleMap;
private address: string;
private _elements: HTMLCollectionOf<Element>;
private _searchBarElement: HTMLInputElement;
private _lat: number;
private _long: number;
private _geoLat: string;
private _geoLong: string;
private _completedText: string;
service;
newLocation: LatLng;
  constructor(  public navParams: NavParams, public _popoverCtrl: PopoverController, public _popoverPage: PopoverPageComponent, private _mapService: MapServiceProvider, private _geocoder: NativeGeocoder, public _modalCtrl: ModalController, private _googleMaps: GoogleMaps, public navCtrl: NavController, private _geoLocation: Geolocation ) {
 this.address = "";
 this._completedText = "";

  }

  ionViewDidLoad(){
    this._geoLocation.getCurrentPosition().then((resp) => {  
      this._lat = resp.coords.latitude; 
      this._long = resp.coords.longitude; 
    }).then(() => this.InitLocation());
  }

  InitElements(spliceThisArray: string[]){
    spliceThisArray.splice(0);
   
  }

InitLocation(){
      let location = new LatLng(this._lat, this._long);
      this.map = new GoogleMap('map', {
      'mapType': 'MAP_TYPE_SATELLITE',
       'controls': {
        'compass': true,
        'myLocationButton': true,
        'indoorPicker': true,
        'zoom': true, 
       },
       'gestures': {
         'scroll': true,
         'tilt': true,
         'zoom': true,
         'rotate': true
       },
       'camera': {
         'target': location,
         'tilt': 30,
         'zoom': 15,
         'bearing': 50
       }
    });
      this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
        console.log("map is ready");
      })
  }
createPopover(myEvent){
  
  this._mapService.getMap(this.service, this.map);
  let myPop = this._popoverCtrl.create(PopoverPageComponent);
     myPop.present({
      ev: myEvent});
  
}

selectItem(item, i){
  this._geocoder.forwardGeocode(item)
   .then((Coordinates: NativeGeocoderForwardResult) =>  { this._geoLat = Coordinates.latitude; this._geoLong = Coordinates.longitude; })
   .then(() => this.getNewPosition())
  
  }

getNewPosition(){
  
  let newPosition = <LatLng> {
    lat: parseFloat(this._geoLat), 
    lng: parseFloat(this._geoLong)
    }
    this.MoveCamera(newPosition);
}

MoveCamera(loc: LatLng){
   let options: CameraPosition<LatLng> = {
       target: loc,
       zoom: 17,
       tilt: 30,
       bearing: 50,
       };
     this.map.moveCamera(options);
   }
 
   presentModal() {
     this.createPopover(event);
    }

}

Popover SearchBar

import { Component } from '@angular/core';
import { MapServiceProvider } from '../../providers/map-service/map-service';
@Component({
  selector: 'popover-page',
  templateUrl: 'popover-page.html',

})
export class PopoverPageComponent {
  _sbelement:any;
  _elements: HTMLCollectionOf<Element>;
  elem: Element;
  text: string;
  places: string[];
  address: string;
  service;
  completeString: string;

  constructor( private _mapService: MapServiceProvider) {
    this.address = "";
    this.places = [];
    this.completeString = "";
   
  }

  ionViewDidLoad(){   
    console.log('loaded')
   this.InitElements(this.places, this._sbelement);
   this._mapService.emptyList(this._elements);

  }

  ionViewDidLeave(){
    this._sbelement = "";

   for (let i = 0; i < this._elements.length; i++){
     this._elements.item(i).remove();
   }
   this.completeString = "";
  }

  InitElements(spliceThisArray: string[], element){
    
    spliceThisArray.splice(0);
    this._sbelement = document.getElementsByClassName('searchbar-input')[0];
    this._mapService.enterModal(this.service, this._sbelement);
 
  }

makeList(place: Object){
 
  this._elements = document.getElementsByClassName('pac-item');
  this.places = [];
  for (let i = 0; i < this._elements.length; i++){
    this.completeString = this._elements[i].children[1].textContent + " " +  this._elements[i].children[2].textContent;
    this.places.push(this.completeString);
     }
     this._mapService.getElements(this._elements);
  }
}

Provider

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { NativeGeocoder, NativeGeocoderForwardResult, NativeGeocoderReverseResult } from '@ionic-native/native-geocoder';
import { GoogleMaps, GoogleMap, LatLng, LatLngBounds } from '@ionic-native/google-maps';
declare var google;
import 'rxjs/add/operator/map';
export interface geoResults {
  lat: number;
  lng: number;
}
@Injectable()
export class MapServiceProvider {
private _lat: number;
private _long: number;
private _geoResults: geoResults;
public _addresses: string[];
public _latLng: LatLng;
public _bounds: LatLngBounds;
service: any;
myMap: GoogleMap;
input: HTMLInputElement;
elems: HTMLCollectionOf<Element>;

  constructor(private _geocoder: NativeGeocoder, public http: Http) {
    this._addresses = [];
    
  }

 ionViewDidLoad(){

 }

  returnCoordinates(item: string){
    this._geocoder.forwardGeocode(item).then((Coordinates: NativeGeocoderForwardResult) => { 
      this._lat = parseFloat(Coordinates.latitude); 
      this._long = parseFloat(Coordinates.longitude) 
    })
   return this._geoResults = {
      lat: this._lat,
      lng: this._long
    }
  
  }

  getItems(arr){
  this._addresses = arr;
  }

  getMap(map: GoogleMap, serv){
    this.myMap = map;
    this.service = serv;
  } 
  


enterModal(serv, input){
  serv = new google.maps.places.Autocomplete(input);
}
getElements(arr: HTMLCollectionOf<Element>){
console.log(arr);
}
returnElements(){

}
emptyList(eles: HTMLCollectionOf<Element>){
if (eles !== undefined){
  let len = eles.length;
   for ( let i = 0; i < len; i++){
console.log(eles[i])
        }
      }
   }
}

Again, I’m just getting started so some of the stuff isn’t even being used, just messing around. You should be able to extract what you need though. Sorry i didn’t format it to make it more presentable.

in index html

<script src="https://maps.googleapis.com/maps/api/js?key=*************&libraries=places";
   "https://maps.googleapis.com/maps/api/js?key=************&callback=initMap" async defer></script>
<!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

Map Component’s scss, this is important

ion-app._gmaps_cdv .nav-decor {
    background-color: transparent !important
}
.pac-container {
    display: none;
    pointer-events: auto;
}
.pac-item {
    z-index: 10001 !important;
}
.item-ios {
    font-size: 1.4rem;
}

page-map {
 
    .flex-container {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .list-container {
        height: 30%;
    }
    .map-container {
        height: 65%;

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

}

Notice .pac-container, and how I have it set not to display. That’s because I created the custom SearchBar. To set it to work on the map component, change it to…

.pac-container {
z-index: 10000;
pointer-events: auto;
}

Custom SearchBar scss, actually in app.scss to override the popover.

.popover-content, .popover-ios {
    width: 100% !important;
    position: absolute;
    left: 0 !important;
    background-color: transparent !important;


}

the z-index is a necessity or it wont show the list of results.
You also have to set your info up in Google’s developer console to active your API Key’s.
Good Luck!

this is the error .when i select any item form list menu.

also there is a one problem map is not loading.

@addwebsolution Here is my full code.
index.html
here i’m put this line.
<script src="http://maps.google.com/maps/api/js?key=AIzaSyAEEC0OzbKyyPEHc-vHUp_bXRVcNEyyl5w&libraries=places"></script>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
///
import { Geolocation } from '@ionic-native/geolocation';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Geolocation,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
**home.ts**
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);
     
      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);
      });
    });
  }

}

home.html

<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>

what i’m wrong?

@addwebsolution Hey! are you there?

Hi! I’m very interested in this post. So if someone have some update, share it please :slight_smile:

Have you find a solution for your problem? I want to create an app that geolocates me and shows me the point of interests around me.

Error:
geolocation access has been blocked because of a feature policy applied to the current document.
please help to resolve this freakin problem

just add
npm install @types/googlemaps --save-dev

2 Likes

Hi mate, I there is a nice tutorial here.