sar*_* va 3 google-maps autocomplete angular
我在我的角度项目中使用AGM提出Google地址建议。如果用户未选择任何地址,我想选择第一个地址。
请任何人为此提供一些建议。
提前致谢。
经过大量的时间寻找解决方案后,终于找到了解决方案,
如果您已经在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);
}
}
Run Code Online (Sandbox Code Playgroud)
地点预测服务
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);
}
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
对我来说,它是有效的,如果您遇到任何问题,请添加您的评论(或向我发送电子邮件@ saravanava3@gmail.com),如果我知道您的查询,我会回复
| 归档时间: |
|
| 查看次数: |
6489 次 |
| 最近记录: |