我正在尝试在ReactJS上使用Google Maps Api,并尽可能使用最少的npm模块。所以我自己将脚本添加到window对象。但是Typescript跳了句谚语:“属性'google'在类型'Window'上不存在”。
我尝试在窗口界面中添加一个属性google:any,但是它不起作用,并且我无法在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;
并且它仍然返回相同的错误。
答案 0 :(得分:0)
您需要Google Map的TypeScript定义,这可以通过命令npm i @types/googlemaps --save-dev
答案 1 :(得分:0)
为什么使用window.google
而不是这样
只需将其添加到您课堂外的顶部
declare const google: any;
然后像这样使用。
map: new google.maps.Map(document.getElementById("map"),
或安装键入内容。
答案 2 :(得分:0)
对于我而言,对我有用的解决方法是将其作为<script>
标签添加到index.html
中。
好处是,现在您不需要使用withScriptjs
并在每个组件上都有一个mapURL
。
答案 3 :(得分:0)
如果您想从窗口访问谷歌地图属性(如果它已经加载),这可能会有所帮助。
const { maps } = (window as any).google;