我正在尝试在 ReactJS 上使用尽可能少的 npm 模块的 Google Maps Api。所以我自己将脚本添加到窗口对象。但是 Typescript 在说了一句之后跳了起来:“属性 'google' 在类型 'Window' 上不存在”。
我尝试将属性 google: any 添加到 Window 界面但它不起作用,并且我在 google 类型中找不到正确的界面。
这是我的代码:
private initMap = () => {
this.setState({
map: new window.google.maps.Map(document.getElementById("map"), {
center: {
lat: this.state.userPosition.lat,
lng: this.state.userPosition.lng
},
zoom: this.state.zoom,
mapTypeId: window.google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
})
});
this.setState({
rangeCircle: new window.google.maps.Circle({
strokeColor: "#007AFF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#007AFF",
fillOpacity: 0.35,
map: this.state.map,
center: {
lat: this.state.userPosition.lat,
lng: this.state.userPosition.lng
},
radius: this.state.radius * 1000
})
});
this.setState({
centerMarker: new window.google.maps.Marker({
icon: { locationIcon },
map: this.state.map,
position: this.state.userPosition
})
});
};
private renderMap = () => {
loadScript(
"https://maps.googleapis.com/maps/api/js?key=*********&callback=initMap"
);
window.initMap = this.initMap;
};
}
function loadScript(url: string) {
const index = window.document.getElementsByTagName("script")[0];
const script = window.document.createElement("script");
script.src = url;
script.async = true;
script.defer = true;
if (index.parentNode) {
index.parentNode.insertBefore(script, index);
}
}
- - - - - - - 更新 - - - - - - - - -
我创建了这个界面:
interface IGoogle {
maps: {
Circle: google.maps.Circle;
Map: google.maps.Map;
Marker: google.maps.Marker;
}
}
并在 Window 中添加了一个 google 属性:
interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch, WindowOrWorkerGlobalScope, WindowEventHandlers {
google: IGoogle;
initMap: () => void;
它仍然返回相同的错误。
最佳答案
您需要 Google Map 的 TypeScript 定义,这可以通过命令 npm i @types/google.maps --save-dev
来实现
修订:根据 @timarcosdias , 包更新为 @types/google.maps
关于reactjs - 类型 'google' 上不存在属性 'Window',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55464196/