我在我的 Angular 项目中使用 AGM 来获取谷歌地址建议。如果用户没有选择地址,我想要 选择第一个地址。
请问有人可以给出一些建议吗?
先行感谢。
请问有人可以给出一些建议吗?
先行感谢。
经过漫长的搜索终于找到了解决方案,
如果您已经在 Angular 2、4、5 和 6 中实现了 Google 地址建议(自动完成)并想要默认选择第一个建议,那么我们提供了一个可行的示例:
我们需要单独创建一个服务并进行订阅。下面是一个可以运行的示例:
重要提示:请耐心地查看并修改名称等内容,这样做肯定会奏效。
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 & 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),如果我了解您的问题,我会回复您。
我无法使其工作。可能是因为使用了Angular 7。这里是我使用BehaviorSubject的尝试。
最初的回答
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 { }
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;
}
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);
}
});
}
}
<h2>Google Places Test</h2>
<p>Angular 7 & 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>
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);
}
}