简体   繁体   中英

Reactjs react-google-maps undefined

I am working with the react-google-maps package https://github.com/tomchentw/react-google-maps and https://www.npmjs.com/package/react-google-maps . I have an error that says:

./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

and heres my line in the error:

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

all the 'google' thing is error.

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

If google is not defined, than you didn't load Google Maps API correctly. As explained in react-google-maps 's README , put this in your HTML before your React component code loads:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM