代码之家  ›  专栏  ›  技术社区  ›  anon

未定义“谷歌”:在React JS[重复]中添加谷歌地图API

  •  7
  • anon  · 技术社区  · 8 年前

    我在我的 index.html 文件,如下所示:

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

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

    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脚本。然而,它没有定义。

    有什么想法吗?Tnx提前!

    1 回复  |  直到 5 年前
        1
  •  26
  •   anon anon    8 年前

    好的,这似乎有效:

    解决方案是隐式定义 google

    const google = window.google
    

    回答如下:

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

    推荐文章