javascript - “Google”未定义 : adding Google Maps API in React JS

标签 javascript google-maps

<分区>

这里是 React JS 新手,所以请多多包涵。

我在我的 index.html 文件中添加了 Google Maps API 脚本,如下所示:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">

  </head>
  <body>
    
    <div id="root"></div>
  
    <script src="https://maps.googleapis.com/maps/api/js?key=MY-API-IS-HERE"></script>
  </body>
</html>

然后,我使用 npm 安装了 google-maps-react,这样我就可以使用它的组件了。我像这样在我的组件中导入了这个库:

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

class BaseMap extends Component {
    constructor() {
        super();
        this.state = {
            center: {lat: 42, lng: 14},
            zoom: 10
        }
    };

    render() {
        let location = {
            center: '',
            zoom: ''
        }

        return (
            <GoogleMapReact>
            </GoogleMapReact>
        );
    }

    myMethod(){
        let geocoder = new google.maps.Geocoder(); 
    }
}

export default BaseMap;

但是,当我尝试使用 google.maps.Geocoder 时,我得到:

Line 30:  'google' is not defined  no-undef

据我所知,google 应该是一个全局窗口对象,因为我在 html 文件中包含了 Google Maps API 脚本。但是,它没有定义。

有什么想法吗?提前发送!

最佳答案

好的,这似乎可行:

解决方案是在类上方的变量中隐式定义 google,如下所示:

const google = window.google

在这里回答:

google is not defined in react app using create-react-app

关于javascript - “Google”未定义 : adding Google Maps API in React JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46122905/

相关文章:

javascript - 停止执行 javascript 直到整个周期

javascript - 具有可变列布局的响应式网格

c# - asp.net 使用 Jquery 调用异步 webMethod

actionscript-3 - 获取国家边界

java - 触摸时不显示 Google map 对话框/信息窗口

javascript - 更改所选选项的颜色(选中时)

javascript - 在IE9中设置currentTime

android - 如何将 map 放置在选项卡式 Android 应用程序的选项卡中

google-maps - 学习 geokit-rails3

ios - Google places api 应该只返回地址