Reactjs react-google-maps undefined

时间:2017-08-18 02:13:23

标签: javascript google-maps reactjs google-maps-api-3 maps

我正在使用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}`);
        }
    });
}

所有' google'事情是错误的。

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

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

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