【问题标题】:Ionic - Google places and Autocomplete locationIonic - Google 地方和自动填充位置
【发布时间】:2017-07-14 15:39:34
【问题描述】:

我在 Ionic 2 的项目上工作,到目前为止我已经实现了地图,但我无法摆脱这一点。为了将 Google Place 和 Autocomplete 添加到项目中,我需要了解我应该采取的方式。

我能做什么?

HTML:

<ion-row>
  <ion-item>
    <ion-label>Search</ion-label>
    <ion-input id="places" type="text" name="search"></ion-input>       
</ion-row>
<div #map id="map"></div>

HOME.ts

export class HomePage {

public latitude: number;
public longitude: number;

@ViewChild('map') mapElement;
map: any;
marker: any;
search: string;

constructor(public navCtrl: NavController, public platform: Platform) {
 /*platform.ready().then(() => {
  this.InitMap();
 });*/
}
 ionViewDidLoad(){
 this.InitMap();
}

InitMap() {

  this.setLocation();
  let input = document.getElementById('places');
  let autocomplete = new google.maps.places.Autocomplete(input);

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

}

setLocation() {

  let latLng = new google.maps.LatLng(53.550513, 9.994241);
  let mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);    
  this.marker = new google.maps.Marker({
    position: latLng,
    map: this.map,
   });
  }

 }

怎么了? 谢谢

【问题讨论】:

  • 你到底在尝试什么,反应是什么?
  • 正如我所说。我想实现地图的自动完成功能。
  • 你得到了什么输出?
  • 根本行不通。并且什么也不返回。我看不出有什么问题。
  • 让我知道它是否有效

标签: javascript google-maps ionic-framework ionic2


【解决方案1】:

已解决!很长一段时间后,我能够找到解决问题的方法。这是解决方案:

主页.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);
   });
 }
}

【讨论】:

  • 是的,这是完美的使用,但它没有给出纬度和经度,所以你能指导我有 latlang。
  • 你好 Atam_Jeet Singh,你看到了最后的更新。要获取纬度和经度,您需要使用 Geocode 转换地址。
  • 嗨迈克尔,对我来说这个解决方案不起作用,首先我必须添加declare let google: any; 但是当我尝试打开自动完成模式页面时仍然出现这个错误TypeError: Cannot read property 'AutocompleteService' of undefined 你是否也有这个错误?
  • 太棒了!难道我们真的需要一个新的AutoCompletePage 可以直接将google autocompeteservice集成到用户输入的输入框
  • @Kicker Fixes for TypeError: Cannot read property 'AutocompleteService' of undefined 确保在您的 Google JS 声明中包含 libraries=places,即:&lt;script src="http://maps.google.com/maps/api/js?libraries=places&amp;key=xxx"&gt;&lt;/script&gt;
【解决方案2】:

使用 elementref 代替 document.getElementById 访问所使用的离子输入 试试:

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

在你的组件类中,

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

    }

检查角度文档here

【讨论】:

  • 感谢您的回复,但不幸的是它什么也没做。在控制台中我有一个错误:InvalidValueError: not an instance of HTMLInputElement
  • 哦..好吧我会改变我的答案..我认为它有价值
  • 伟大的 Suraj,let autocomplete = new google.maps.places.Autocomplete (this.places.nativeElement); 的许多错误。要显示地图,我需要 @ViewChild ('map') mapElement
  • 正如我所说,我需要@ViewChild ('map') mapElement 才能显示我的地图。如果我添加@ViewChild("places"),则不显示任何内容。这是错误:EXCEPTION: Uncaught (in promise): ReferenceError: google is not defined
  • 这是一个不同的错误。您是否已在全球范围内声明了 google?
【解决方案3】:

如果您只需要“google places object”,那么您的代码可以非常简单,如下所示:

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

在我的代码中:

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

【讨论】:

  • 我已经使用了这个解决方案,它工作正常,但只有在我初始化应用程序时才运行一次。我每次都需要查找 google 地方自动完成功能
猜你喜欢
  • 1970-01-01
  • 2015-01-23
  • 2012-04-27
  • 2015-09-17
  • 1970-01-01
  • 2019-02-04
  • 2014-03-28
  • 2015-06-15
  • 1970-01-01
相关资源
最近更新 更多