Reactjs react-google-maps 未定义

IT技术 javascript google-maps reactjs google-maps-api-3 maps
2021-05-23 00:05:12

我正在使用 react-google-maps 包https://github.com/tomchentw/react-google-mapshttps://www.npmjs.com/package/react-google-maps我有一个错误说:

./src/App.js Line 31:  'google' is not defined  no-undef  Line 32:  'google' is not defined  no-undef  Line 37:  'google' is not defined  no-undef Line 42:  'google' is not defined  no-undef Line 44:  'google' is not defined  no-undef

这是我的错误行:

 state = {
    origin: new google.maps.LatLng(41.8507300, -87.6512600),
    destination: new google.maps.LatLng(41.8525800, -87.6514100),
    directions: null,
}

componentDidMount() {
    const DirectionsService = new google.maps.DirectionsService();

    DirectionsService.route({
        origin: this.state.origin,
        destination: this.state.destination,
        travelMode: google.maps.TravelMode.DRIVING,
    }, (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
            this.setState({
                directions: result,
            });
        } else {
            console.error(`error fetching directions ${result}`);
        }
    });
}

所有“谷歌”的东西都是错误的。

3个回答

答案是我没有将此行包含/* global google */在我的文件顶部。

如果google未定义,则表示您没有正确加载 Google Maps API。react-google-maps的 README 中所述,在加载 React 组件代码之前将其放入 HTML 中

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE"></script>

你也可以只包含窗口引用来解决错误,至少使用默认的 create-react-app 配置它确实如此

new window.google.maps.LatLng(41.8507300, -87.6512600)