“窗口”类型上不存在属性“google”

Lui*_*uis 7 google-maps-api-3 typescript reactjs

我正在尝试在 ReactJS 上使用 Google Maps Api 和尽可能少的 npm 模块。所以我自己将脚本添加到窗口对象中。但是打字稿在一句话之后跳了起来:“属性 'google' 在类型 'Window' 上不存在”。

我尝试在 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
  })
});
Run Code Online (Sandbox Code Playgroud)

};

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

- - - - - - - 更新 - - - - - - - - -

我创建了这个界面:

interface IGoogle {
    maps: {
        Circle: google.maps.Circle;
        Map: google.maps.Map;
        Marker: google.maps.Marker;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在 Window 中添加了一个 google 属性:

interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch, WindowOrWorkerGlobalScope, WindowEventHandlers {
    google: IGoogle;
    initMap: () => void;
Run Code Online (Sandbox Code Playgroud)

它仍然返回相同的错误。

Tia*_*Lin 15

你需要谷歌地图的 TypeScript 定义,这可以通过命令来实现 npm i @types/googlemaps --save-dev

  • 此包已移至`@types/google.maps`。 (2认同)

小智 5

如果您想从窗口访问谷歌地图属性(如果它已经加载),这可能会有所帮助。

const { maps } = (window as any).google;
Run Code Online (Sandbox Code Playgroud)