1

I am stuck figuring out how to manage this error that I am getting after implementing google maps autocomplete in my application. My maps.ts file looks like ;

import { Component, NgZone } from "@angular/core";
import {AlertController, NavController, Platform, NavParams,ModalController } from 'ionic-angular';
import { GoogleMap, GoogleMapsEvent, GoogleMapsLatLng, GoogleMapsMarkerOptions, CameraPosition } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Geolocation } from 'ionic-native';
declare var google:any;
declare var window: any;
import {MapsAPILoader} from 'angular2-google-maps/core';
import { ConnectivityService } from '../../providers/connectivity-service';


@Component({
  selector: 'maps-page',
  templateUrl: 'maps.html'
})
export class MapsPage {
    map: any;
    firstTime : boolean = true;
    isDisplayOfflineMode : boolean = false;
  //private map: GoogleMap;

  constructor(private _navController: NavController,
    private zone: NgZone,
    private  _loader : MapsAPILoader,
    private connectivityService:ConnectivityService,
    private platform: Platform,
    public navParams: NavParams,
    public modalCtrl:ModalController,
    private alert : AlertController,
    private _zone: NgZone) {

    this.platform.ready().then(() => this.onPlatformReady());
    this.map = {
            lat: 0,
            lng: 0,
            zoom: 15
        };
        this.platform.ready().then(() => this.onPlatformReady());
        this.NetworkConnectivity();
  }
  private onPlatformReady(): void {

  }


  ngAfterViewInit() {
    GoogleMap.isAvailable().then(() => {
      this.map = new GoogleMap('map_canvas');
      this.map.one(GoogleMapsEvent.MAP_READY).then((data: any) => {
        this._zone.run(() => {
          let myPosition = new GoogleMapsLatLng(45.495586, -73.574709);
          let position: CameraPosition = {
            target: myPosition,
            zoom: 15
          };
          console.log("My position is", myPosition);
          this.map.moveCamera(position);
        });

      });
    });
  }


  submit() {
    let that = this;
    this.map.getCameraPosition().then(res => {
      let callback = that.navParams.get("callback")
      callback(res.target).then(() => {
        this._navController.pop();
      });
    })
  }
  dismiss() {
    this._navController.pop()
  }


    NetworkConnectivity(){
        setInterval(() => {
            if(this.connectivityService.isOnline()){

                if (this.firstTime)
                {
                    this.loadMap();
                    this.autocomplete()
                }

            } else {
                if(!this.isDisplayOfflineMode)
                    this.displayOffline();

            }
        }, 2000);


    }

    displayOffline() {
        this.isDisplayOfflineMode = true;
        let alert = this.alert.create({
            title: 'Network connectivity',
            subTitle: 'Offline',
            buttons: [{
                text : 'Retry',
                handler: () => {
                    this.isDisplayOfflineMode = false;
                }
            }]

        });
        alert.present();
    }


    autocomplete() {
        this._loader.load().then(() => {
            let autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete').getElementsByTagName('input')[0], {});
            google.maps.event.addListener(autocomplete, 'place_changed', () => {
                let place = autocomplete.getPlace();
                this.map.lat  = place.geometry.location.lat();
                this.map.lng = place.geometry.location.lng();
                console.log(place);
            });
        });
    }


    loadMap(){

        Geolocation.getCurrentPosition().then((position) => {

            this.map = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
                zoom: 15
            };
            this.firstTime = false;
        }, (err) => {
        });

    }

   getDirections() { 
    window.location = `geo:${this.map.lat},${this.map.lng};u=35`; 
  }


}

And my html file looks like;

<ion-header>
  <ion-toolbar>
    <ion-title>
      {{'SEARCHFORM.SELECT' | translate}}
    </ion-title>
    <ion-buttons start>
      <button ion-button (click)="dismiss()">
        <span ion-text color="primary" showWhen="ios">{{'SEARCHFORM.CANCEL' | translate}}</span>
        <ion-icon name="md-close" showWhen="android,windows"></ion-icon>
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-fab left bottom>
        <button ion-fab class="fab-map" (click)="getDirections()">
            <ion-icon name="navigate"></ion-icon>
        </button>
    </ion-fab>

    <ion-item>
        <ion-input id="autocomplete" type="text" name="title" placeholder="Enter Address"></ion-input>
    </ion-item>

    <sebm-google-map id="map" [latitude]="map.lat" [longitude]="map.lng" [zoom]="map.zoom" >
        <sebm-google-map-marker [latitude]="map.lat" [longitude]="map.lng">
            <sebm-google-map-info-window>
                <strong>My location</strong>
            </sebm-google-map-info-window>
        </sebm-google-map-marker>
    </sebm-google-map>
  <div style="height: 100%;" id="map_canvas"></div>
</ion-content>
<ion-footer>
     <button ion-button (click)="submit()">{{'SEARCHFORM.SUBMIT' | translate}}</button>
</ion-footer>

The maps were working fine before I implemented google maps autocomplete but it just crashes now whenever I tap anywhere on the screen. Does anyone know why its happening if anyone went through it and what might be a possible solution? Does my html file look fine? Or is there some other problem. Many thanks!!

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
BleachedAxe
  • 393
  • 2
  • 5
  • 20

1 Answers1

0

Instead of document.getElementById('autocomplete').getElementsByTagName('input')[0], use @ViewChild and ElementRef to get htmlelements in Angular/Ionic 2.

import {ViewChild,ElementRef} from '@angular/core';

@Component({
  selector: 'maps-page',
  templateUrl: 'maps.html'
})
export class MapsPage {
  @ViewChild('autocomp')
  aComplete:ElementRef;

  //...
    autocomplete() {
        this._loader.load().then(() => {
            let autocomplete = new google.maps.places.Autocomplete(this.aComplete.nativeElement.querySelector('input'));

You need to use querySelector because ionic encapsulates the html element within ion-input. Check this answer

In your html use #autocomp as id for the element.

<ion-input #autocomp id="autocomplete" type="text" name="title" placeholder="Enter Address"></ion-input>

Reference: ElementRef,ViewChild

Community
  • 1
  • 1
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • I edited my files just like you wrote but now i get Uncaught (in promise):Type Error:Cannot read property 'querySelector' of undefined TypeError. Cannot read property 'querySelector' of undefined at http://.................. Do you know whats wrong now? Thank you! – BleachedAxe Apr 09 '17 at 04:36
  • what is the output of `console.log(this.aComp);`? – Suraj Rao Apr 09 '17 at 04:50
  • app : App _autoComplete : "off" _autoCorrect : "off" _autoFocusAssist : "immediate" _clearInput : false _componentName : "input" _config : Config _content : Content _disabled : false _dom : DomController _elementRef : ElementRef _form : Form _item : Item _keyboardHeight : 300 _mode : "md" _native : NativeInput _nav : Tab _platform : Platform _renderer : DebugDomRenderer _scrollEnd : Subscriber _scrollStart : Subscriber _type : "text" _useAssist : true _usePadding : true _value : "" blur : EventEmitter clearInput – BleachedAxe Apr 09 '17 at 05:19
  • Yes, it says it is undefined . – BleachedAxe Apr 09 '17 at 05:28
  • this looks like a problem with the recent change.. https://forum.ionicframework.com/t/ion-input-and-the-nativeelement/82049 does this work? – Suraj Rao Apr 09 '17 at 05:43
  • It didn't work, is there any other workaround through this ? Because I really need autocomplete :( – BleachedAxe Apr 09 '17 at 17:43
  • you could just try plain input.. and add some css to it...or try with http://ionicframework.com/docs/api/components/searchbar/Searchbar/ – Suraj Rao Apr 09 '17 at 17:57