Ionic - Google places and Autocomplete location

后端 未结 3 444
北恋
北恋 2020-12-08 14:51

I have work on the project on Ionic 2 and I have implemented the map so far, but I can not get out of that point. I needed to be shown the way I should go in order to add Go

相关标签:
3条回答
  • 2020-12-08 15:05

    Use elementref for accessing the ion input used instead of document.getElementById Try:

    <ion-input #places type="text" name="search"></ion-input> 
    

    In your component class,

     import {Elementref } from '@angular/core'; 
     @ViewChild("places")
      public places: ElementRef;
        InitMap(){
        this.setLocation();
        let autocomplete = new google.maps.places.Autocomplete(this.places.nativeElement);
        google.maps.event.addListener(autocomplete, 'place_changed', () => {
    
            let place = autocomplete.getPlace();
            this.latitude = place.geometry.location.lat();
            this.longitude = place.geometry.location.lng();
            alert(this.latitude + ", " + this.longitude);
            console.log(place);
          });
    
        }
    

    Check angular docs here

    0 讨论(0)
  • 2020-12-08 15:08

    If all you need is "google places object", then your code can be very simple like so:

    <ion-item>
        <ion-label>Search your city</ion-label>
        <ion-input formControlName="placeAutofill" id="googlePlaces" required></ion-input>
    </ion-item>
    

    And in my code:

    ionViewWillEnter() {
       // Google Places API auto complete
       let input = document.getElementById('googlePlaces').getElementsByTagName('input')[0];
       let autocomplete = new google.maps.places.Autocomplete(input, {types: ['geocode']});
       google.maps.event.addListener(autocomplete, 'place_changed', () => {
         // retrieve the place object for your use
         let place = autocomplete.getPlace();
       });
    }
    
    0 讨论(0)
  • 2020-12-08 15:15

    SOLVED! After a long time I was able to find a solution to my problem. Here's the solution:

    Home.html:

    <ion-list>
      <ion-item>
        <ion-input (click)="showAddressModal()" [(ngModel)]="address.place"type="text" placeholder="Pick an address">              </ion-input>
      </ion-item>
    </ion-list>
    

    Home.ts:

    import {Component} from '@angular/core';
    import {NavController, ModalController} from 'ionic-angular';
    import {AutocompletePage} from './autocomplete';
    
    @Component({
      templateUrl: 'build/pages/home/home.html'
    })
    
    export class HomePage {
      address;
    
      constructor(
        private navCtrl: NavController,
        private ModalCtrl:ModalController
      ) {
        this.address = {
          place: ''
        };
      }
    
      showAddressModal () {
        let modal = this.modalCtrl.create(AutocompletePage);
        let me = this;
        modal.onDidDismiss(data => {
          this.address.place = data;
        });
        modal.present();
      }
    }
    

    AutocompletePage.html:

    <ion-header>
      <ion-toolbar>
        <ion-title>Enter address</ion-title>
        <ion-searchbar [(ngModel)]="autocomplete.query" [showCancelButton]="true"   (ionInput)="updateSearch()" (ionCancel)="dismiss()"></ion-searchbar>
      </ion-toolbar>
    </ion-header>
    
    <ion-content>
      <ion-list>
        <ion-item *ngFor="let item of autocompleteItems" tappable   (click)="chooseItem(item)">
          {{ item }}
        </ion-item>
      </ion-list>
    </ion-content>
    

    AutocompletePage.ts:

    import {Component, NgZone} from '@angular/core';
    import {ViewController} from 'ionic-angular';
    
    @Component({
      templateUrl: 'build/pages/home/autocomplete.html'
    })
    
    export class AutocompletePage {
      autocompleteItems;
      autocomplete;
    
      latitude: number = 0;
      longitude: number = 0;
      geo: any
    
      service = new google.maps.places.AutocompleteService();
    
      constructor (public viewCtrl: ViewController, private zone: NgZone) {
        this.autocompleteItems = [];
        this.autocomplete = {
          query: ''
        };
      }
    
      dismiss() {
        this.viewCtrl.dismiss();
      }
    
      chooseItem(item: any) {
        this.viewCtrl.dismiss(item);
        this.geo = item;
        this.geoCode(this.geo);//convert Address to lat and long
      }
    
      updateSearch() {
    
        if (this.autocomplete.query == '') {
         this.autocompleteItems = [];
         return;
        }
    
        let me = this;
        this.service.getPlacePredictions({
        input: this.autocomplete.query,
        componentRestrictions: {
          country: 'de'
        }
       }, (predictions, status) => {
         me.autocompleteItems = [];
    
       me.zone.run(() => {
         if (predictions != null) {
            predictions.forEach((prediction) => {
              me.autocompleteItems.push(prediction.description);
            });
           }
         });
       });
      }
    
      //convert Address string to lat and long
      geoCode(address:any) {
        let geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address }, (results, status) => {
        this.latitude = results[0].geometry.location.lat();
        this.longitude = results[0].geometry.location.lng();
        alert("lat: " + this.latitude + ", long: " + this.longitude);
       });
     }
    }
    
    0 讨论(0)
提交回复
热议问题