在我的角度项目中使用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);
}
}
地方预测.服务.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 的尝试。
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;
}
地方预测.服务.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 & 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);
}
}
结果