react-google-maps:找不到命名空间“google”

The*_*oul 5 google-maps typescript reactjs

我正在尝试使用这个库“react-google-maps”在我的应用程序中显示谷歌地图。从他们的 github 页面按照教程进行操作后,我在第一次运行时收到此错误(这是一个 create-react-app + typescript 应用程序):

在此处输入图片说明

我有点迷失在这里。以前有人用过这个库吗?这是我的代码:

import * as React from 'react';
import { GoogleMap, Marker, withGoogleMap, withScriptjs } from 'react-google-maps';
import { compose, withProps } from 'recompose';

const TerrMap: React.StatelessComponent<{
    isMarkerShown: boolean
}> = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=__my_api_key__&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
      }),
      withScriptjs,
      withGoogleMap
)( (props: any) => {

    return (
        <GoogleMap
            defaultZoom={8}
            defaultCenter={{ lat: -34.397, lng: 150.644 }}
        >
            {props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} />}
        </GoogleMap>
    );
} ) as any;
Run Code Online (Sandbox Code Playgroud)

小智 8

如果这还没有得到回答。这是解决此问题的方法。

  1. 添加这两个打字"@types/googlemaps"和"@types/markerclustererplus"
  2. 确保在 for 项目中包含这些类型。你可以用不同的方式来做,但最简单的方法是像这样在你的 tsconfig.json 文件中添加这两种类型。

——

{
    "compilerOptions":{
        ...,
        "types":[
            ...
            "googlemaps",
            "markerclustererplus"
        ] 
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题。

  • 2021:我必须添加“google.maps”而不是“googlemaps” (3认同)

小智 2

您必须在文件顶部添加此符号

/*global google*/
Run Code Online (Sandbox Code Playgroud)

我希望这个对你有用