我在应用中使用 Angular Google map ,但无法使用 google.maps.places.PlaceResult
作为代码中重要变量的类型。
我正在实现此代码:(向下滚动到添加位置/地点搜索栏)
我正在 map 上进行地点搜索,但收到此错误:
在此代码中:
ngOnInit() {
// Load places autocomplete
this.maps.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.geoCoder;
let autocomplete = new google.maps.places.autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
// Get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
// Verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
// Set latitude, longitude & zoom
this.userLat = place.geometry.location.lat();
this.userLng = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
我只是按照这个例子,但它似乎无法识别google
。你如何解决这个问题?
我希望按原样使用链接中的示例,但我不能。
提前致谢!
最佳答案
要解决此问题,您需要在名为 types
的文件夹内的根文件夹中添加一个名为 google-maps.d.ts
的文件。
然后在该文件中添加以下代码:
google-maps.d.ts
import '@types/googlemaps';
declare global {
interface Window {
google: typeof google;
}
}
这将允许您在 typescript 中为变量指定 google.X.X
类型。确保您的项目中安装了类型,npm install --save @types/googlemaps
。
此外,请确保在 tsconfig.json
文件中添加 types
,以将其指向包含以下代码的文件夹:
tsconfig.json
// tsconfig.json
compilerOptions: {
...
"typeRoots": [
"node_modules/@types",
"types"
],
...
}
我从哪里得到答案,(向下滚动到 feilxmosh
的第二个答案):
How to install Typescript typings for google maps
感谢 @JensHabegger 向我发送此链接。我回答了我自己的问题,因为 JensHabegger 没有回答。
关于angular - 如何修复 Angular Google map 中的类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653284/