我已经制定了一个自定义指令来使用 google api 自动完成功能,并尝试减少对 google 的 api 调用次数,因为 这是我的代码。
请建议我设置一些延迟,以减少对谷歌服务器的 api 调用以实现输入自动完成功能
此代码按字母输入调用 api 我想在 4 到 5 秒后或键入单词后进行
//Google-place-directive.ts
import {
Directive,
ElementRef,
OnInit,
Output,
EventEmitter
} from "@angular/core";
declare var google: any;
@Directive({
selector: "[google-place]"
})
export class GooglePlacesDirective implements OnInit {
@Output() onSelect: EventEmitter<any> = new EventEmitter();
private element: HTMLInputElement;
constructor(elRef: ElementRef) {
//elRef will get a reference to the element where
//the directive is placed
this.element = elRef.nativeElement;
}
getFormattedAddress(place) {
//@params: place - Google Autocomplete place object
//@returns: location_obj - An address object in human readable format
let location_obj = {};
console.log(place);
console.log(place.geometry.location.lat());
console.log(place.geometry.location.lng());
for (let i in place.address_components) {
let item = place.address_components[i];
location_obj["formatted_address"] = place.formatted_address;
if (item["types"].indexOf("locality") > -1) {
location_obj["locality"] = item["long_name"];
} else if (item["types"].indexOf("administrative_area_level_1") > -1) {
location_obj["admin_area_l1"] = item["short_name"];
} else if (item["types"].indexOf("street_number") > -1) {
location_obj["street_number"] = item["short_name"];
} else if (item["types"].indexOf("route") > -1) {
location_obj["route"] = item["long_name"];
} else if (item["types"].indexOf("country") > -1) {
location_obj["country"] = item["long_name"];
} else if (item["types"].indexOf("postal_code") > -1) {
location_obj["postal_code"] = item["short_name"];
}
}
return location_obj;
}
ngOnInit() {
const autocomplete = new google.maps.places.Autocomplete(this.element);
//Event listener to monitor place changes in the input
google.maps.event.addListener(autocomplete, "place_changed", () => {
//Emit the new address object for the updated place
this.onSelect.emit(this.getFormattedAddress(autocomplete.getPlace()));
});
}
}
//html就像
<input
type="text"
class="google-place-input"
google-place
(onSelect)="setAddress($event)"
placeholder="Type to search.."
/>
提前致谢