【问题标题】:Angular 6, AGM selects first address in google autocompleteAngular 6,AGM 在谷歌自动完成中选择第一个地址
【发布时间】:2019-01-16 11:04:14
【问题描述】:

我在我的 Angular 项目中使用 AGM 来提供谷歌地址建议。如果用户没有选择,我想选择第一个地址

请任何人为此提出一些建议。

提前致谢。

【问题讨论】:

    标签: angular google-maps autocomplete


    【解决方案1】:

    花了这么多时间寻找解决方案终于找到了,

    如果您已经在 Angular 2,4 5 & 6 中实现了谷歌地址建议(自动完成)并希望默认选择第一个建议,这里我们以工作示例为例,

    我们必须单独创建一个服务并且需要订阅它。我在下面给出了工作示例,

    重要提示:请耐心研究它并更改名称和所有它肯定会起作用。


    app.component.ts

    import { Component } from '@angular/core';
    import { MapsAPILoader } from '@agm/core';
    import { PlacePredictionService } from './place-prediction.service';
    
    import { Observable } from 'rxjs/Observable';
    
    @Component({
       selector: 'app-root',
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      private searchTerm: string;
      private results$: Observable<any[]>;
    
      testResult = [{description: 'test'},{description: 'test'}];
    
      constructor(
        private mapsAPILoader: MapsAPILoader,
        private placePredictionService: PlacePredictionService
      ){}
    
      onSearch(term: string){
    
      this.searchTerm = term;
    
      if (this.searchTerm === '') return;
    
      this.results$ = this.placePredictionService.getPlacePredictions(term);
    
     }
    
    }
    

    place-prediction.service.ts

    import { Injectable } from "@angular/core";
    import { MapsAPILoader } from "@agm/core";
    
    import { Observable } from "rxjs/Observable";
    
    import "rxjs/add/observable/of";
    import "rxjs/add/observable/bindCallback";
    
    @Injectable()
    export class PlacePredictionService {
      private autocompleteService;
    
      constructor(private mapsAPILoader: MapsAPILoader) {
    
        this.mapsAPILoader.load().then(() => {
          this.autocompleteService = new 
          google.maps.places.AutocompleteService();
        });
    
      }
    
      // Wrapper for Google Places Autocomplete Prediction API, returns 
      observable
    
      getPlacePredictions(term: string): Observable<any[]> {
        return Observable.create(observer => {
        // API Call
    
        this.autocompleteService.getPlacePredictions({ input: term }, data => {
          let previousData: Array<any[]>;
    
          // Data validation
    
          if (data) {
            console.log(data);
            previousData = data;
            observer.next(data);
            observer.complete();
          }
    
          // If no data, emit previous data
    
          if (!data) {
            console.log("PreviousData: ");
            observer.next(previousData);
            observer.complete();
    
            // Error Handling
    
          } else {
            observer.error(status);
          }
    
        });
    
        });
    
        }
      }
    

    app.component.html

    <h1>Google Places Test</h1>
    
    <p>Angular 5 &amp; RxJS refresher</p>
    
    <input
      type="search"
      placeholder="Search for place" 
      autocomplete="off"
      autocapitalize="off"
      autofocus
      #search
      (keyup)="onSearch(search.value)"/> 
    
     <p>{{ searchTerm }}</p>
    
     <ul>
    
       <li *ngFor="let result of results$ | async "> {{result.description}} 
       </li>
    
     </ul>
    

    对我来说它是有效的,如果您遇到任何问题,请添加您的评论(或给我发邮件@saravanava3@gmail.com),如果我知道您的查询,我会回复

    【讨论】:

    • 谢谢!你拯救了我的一天!它就像一个魅力!
    【解决方案2】:

    我无法让它工作。可能是因为使用了 Angular 7。这是我使用 BehaviorSubject 的尝试。

    app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AgmCoreModule } from '@agm/core';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AgmCoreModule.forRoot({
          apiKey: 'YOUR API KEY',
          libraries: ['places']
        })
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    google-result.model.ts

    export interface GoogleResult {
      description: string;
      id: string;
      matched_substrings: Matchedsubstring[];
      place_id: string;
      reference: string;
      structured_formatting: Structuredformatting;
      terms: Term[];
      types: string[];
    }
    
    interface Term {
      offset: number;
      value: string;
    }
    
    interface Structuredformatting {
      main_text: string;
      main_text_matched_substrings: Matchedsubstring[];
      secondary_text: string;
    }
    
    interface Matchedsubstring {
      length: number;
      offset: number;
    }
    

    place-prediction.service.ts

    import { Injectable } from '@angular/core';
    import { MapsAPILoader } from '@agm/core';
    import { Observable, BehaviorSubject } from 'rxjs';
    import { GoogleResult } from './google-result.model';
    
    declare var google: any;
    
    @Injectable({
      providedIn: 'root',
    })
    export class PlacePredictionService {
      private data: BehaviorSubject<any> = new BehaviorSubject<any>([]);
      currentData = this.data.asObservable();
    
      public autocompleteService: any;
    
      constructor(private mapsAPILoader: MapsAPILoader) {
        this.mapsAPILoader.load().then(() => {
          this.autocompleteService = new google.maps.places.AutocompleteService();
        });
      }
    
      getPlacePredictions(term: string): Observable<Object[]> {
        return this.autocompleteService.getPlacePredictions({ input: term }, (data: GoogleResult[]) => {
          if (data) {
            console.log(data);
            this.data.next(data);
          }
        });
      }
    }
    

    app.component.html

    <h2>Google Places Test</h2>
    
    <p>Angular 7 &amp; RxJS refresher</p>
    
    <input
      type="search"
      placeholder="Search for place"
      autocomplete="off"
      autocapitalize="off"
      autofocus
      #search
      (keyup)="onSearch(search.value)"
    />
    
    <p>{{ searchTerm }}</p>
    
    <ul>
      <li *ngFor="let result of googlePlacesResults">
        <p>{{ result.description }}</p>
      </li>
    </ul>
    

    app.component.ts

    import { Component, OnInit } from '@angular/core';
    
    import { PlacePredictionService } from './place-prediction.service';
    import { GoogleResult } from './google-result.model';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
      searchTerm: string;
      googlePlacesResults: GoogleResult[] = [];
    
      title = 'google-place-prediction';
    
      constructor(private placePredictionService: PlacePredictionService) {}
    
      ngOnInit() {
        this.getData();
      }
    
      getData() {
        this.placePredictionService.currentData.subscribe((response: GoogleResult[]) => {
          this.googlePlacesResults = response;
        });
      }
    
      onSearch(term: string) {
        this.searchTerm = term;
    
        if (this.searchTerm === '') {
          return;
        }
    
        this.placePredictionService.getPlacePredictions(term);
      }
    }
    

    results

    【讨论】:

    • 我认为您需要在 getData() 中进行更改,在 onSearch() 函数中您必须将响应值分配给一个变量,在该变量中您将获得第一个建议。
    猜你喜欢
    • 2018-06-01
    • 2021-04-23
    • 2019-06-02
    • 2013-07-14
    • 1970-01-01
    • 2013-03-20
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多