【问题标题】:Reactjs react-google-maps undefinedReactjs react-google-maps 未定义
【发布时间】:2018-01-26 14:23:57
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 能详细回答吗?
    • 这个错误是由 Eslint 引起的,你可以尝试在文件顶部添加 /* global google */ 来禁用 ESlint。
    【解决方案2】:

    如果未定义 google,则说明您未正确加载 Google Maps API。正如react-google-maps's README 中解释的那样,将它放在你的 HTML 你的 React 组件代码加载之前:

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

    【讨论】:

    • 如果您在 HTML 中添加脚本标签,然后在渲染函数中,当您将道具传递给组件时,它需要一个道具 googleMapURL 并使用 API 密钥传递 URL 将生成此警告:You have included the Google Maps API multiple times on this page. This may cause unexpected errors.跨度>
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2018-02-17
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多