reactjs - 类型 'google' 上不存在属性 'Window'

标签 reactjs typescript google-maps-api-3

我正在尝试在 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/

相关文章:

typescript - 将对象元组映射到 typescript 类型中的对象

android - 通过 Phonegap 的谷歌导航 Intent

php - 如何使用 Google Map API 计算并显示特定地点的风向?

javascript - 如何在 React 中的 window.open 中使用 Google 字体

javascript - Typescript 中的工厂函数使用和不使用 new 关键字声明文件

angular - 带有 Angular 和 Typescript 的策略模式

java - 如何在android中更改位置更改时更改标记位置

reactjs - 测试 React 类是否属于类型

reactjs - Redux - 如何从另一个 Action 创建者内部调用一个 Action 创建者?

reactjs - 在 React.js 中的耗时操作之前加载消息