我正在构建一个简单的Google Places Autocomplete Angular2指令,但问题是无法获得任何预测(响应始终为空?!)...
作为概念证明,我创建了最简单的代码片段作为参考:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=[MY_API_KEY]&libraries=places" async defer></script>
</head>
<body>
<button type="button" onclick="go()">go</button>
<input id="autocomplete" type="text"></input>
<script>
var autocomplete = null;
function go() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
}
</script>
</body>
</html>
上面的代码有效 - 单击Go按钮后我可以得到预测 .
现在,Angular2场景:
我的_Layout.cshtml文件在head部分中有以下标记:
<script src="https://maps.googleapis.com/maps/api/js?key=[MY_API_KEY]&libraries=places" async defer></script>
我的指示:
import { Directive, ElementRef, Input } from '@angular/core';
declare var google: any;
@Directive({ selector: '[googleplaces]' })
export class GooglePlacesDirective {
autocomplete: any;
constructor(private el: ElementRef) {
}
ngAfterContentInit() {
this.autocomplete = new google.maps.places.Autocomplete(
(this.el.nativeElement),
{ types: ['geocode', 'cities'] });
}
}
而简单的Angular组件:
<form [formGroup]="companyForm">
.
.
.
<div class="form-group">
<label for="Location">Location</label>
<input type="text"
class="form-control"
id="Location"
fromControlName="Location"
googleplaces>
</div>
</form>
场景2(角度)不起作用 . 事实:
-
autocomplete已初始化(它具有所有预期的属性/方法,占位符为"Enter a location"等...)
-
autocomplete不会返回任何类型搜索字符串的预测(它只返回“/**/xdc._le3zv3&&xdc._le3zv3([4))"))
此外,谷歌API控制台说一切都是应该的?!这是截图:
这里有什么问题?谢谢...
2 回答
使用
@ Habeeb的答案是一个很好的开始,但这是一个更清洁的实现 . 首先安装googlemaps typings
npm install --save-dev @types/googlemaps
并将其导入应用import {} from '@types/googlemaps'
中的某个位置 .