简体   繁体   English

react-google-maps “'google' 未定义”错误

[英]react-google-maps “'google' is not defined” error

I am creating a web that utilizes react-google-maps and I am getting a bunch of undefined errors.我正在创建一个使用 react-google-maps 的网络,但遇到了一堆未定义的错误。 I am new to react/js world so any help would be much appreciated.我是 react/js 世界的新手,所以任何帮助都将不胜感激。 Here's the exact errors:这是确切的错误:

Failed to compile.

./src/App.js
  Line 23:  'lifecycle' is not defined  no-undef
  Line 25:  'google' is not defined     no-undef
  Line 28:  'google' is not defined     no-undef
  Line 29:  'google' is not defined     no-undef
  Line 30:  'google' is not defined     no-undef
  Line 32:  'google' is not defined     no-undef

Here's the code:这是代码:

import React, { Component } from 'react';
import './App.css';
import { compose, withProps } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"
const MapWithDirections = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `800px`, width: '800px'}} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
    lifecycle({
        componentDidMount() {
            const DirectionsService = new google.maps.DirectionsService();

            DirectionsService.route({
                origin: new google.maps.LatLng(45.29233869999999, -70.06117489999997),
                destination: new google.maps.LatLng(45.3570637, -70.06257679999999),
                travelMode: google.maps.TravelMode.DRIVING,
            }, (result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                    this.setState({
                        directions: result,
                    });
                } else {
                    console.error(`error fetching directions ${result}`);
                }
            });
        }
    })
)((props) =>
    <GoogleMap
        defaultZoom={8}
        defaultCenter={{ lat: -34.397, lng: 150.644 }}
    >
        {props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} />}
    </GoogleMap>
)


class App extends Component {
  render() {
    return (
      <div className="App">
          <MapWithDirections/>
      </div>
    );
  }
}

export default App;

It looks like I am failing to properly import google maps but looking at the example, it shouldn't have to.看起来我没有正确导入谷歌地图,但看看这个例子,它不应该有。 Any ideas?有任何想法吗?

You can try this new window.google.maps你可以试试这个new window.google.maps

It works for me!这个对我有用!

Example:例子:

<Marker
  icon={{
    url:"../../assets/img/carz.png",
    anchor: new window.google.maps.Point(10, 10),
    scaledSize: new window.google.maps.Size(20, 20)
  }}
/>

You have missed the import of both lifecycle and google.你错过了生命周期和谷歌的导入。 In the example you can see,在示例中,您可以看到,

const { compose, withProps, lifecycle } = require("recompose"); const { compose,withProps, lifecycle } = require("recompose");

and the import of google is not mentioned in the example but that too should be imported.并且示例中没有提到 google 的导入,但也应该导入。

Regarding importing google, it's to do with eslint validation not JS.关于导入 google,它与 eslint 验证有关,而不是 JS。 do the following change:做以下更改:

PlacesAutocomplete.js Line 1: PlacesAutocomplete.js 第 1 行:

/*global google*/

^ this will declare to eslint that google is a global name and will be available at runtime. ^ 这将向 eslint 声明 google 是一个全局名称,并将在运行时可用。 For more info you can go thru this git page有关更多信息,您可以浏览此git 页面

I don't know why, but with Angular and React you need to add a script tag for this kind of libraries, like this:我不知道为什么,但是对于 Angular 和 React,您需要为此类库添加脚本标记,如下所示:

<body>
...
    <script src="https://maps.googleapis.com/maps/api/js?key=<API KEY>&callback=init"
    async defer></script>
</body>

If you check inside, you can find a definition to window.google:如果您查看内部,您可以找到 window.google 的定义:

window.google = window.google || {};

You will need to use window.google instead this.props.google in this case.. I will try to find a better way to use the library, but this is my contribution to this unknown problem...在这种情况下,您将需要使用 window.google 而不是 this.props.google .. 我将尝试找到一种更好的方式来使用该库,但这是我对这个未知问题的贡献......

I have to face this problem when I try to draw a circle in google map component so I create for the map component and I handle that problem in componentDidUpdate with using try-catch because it runs much time when the component render.当我尝试在 google map 组件中绘制一个圆圈时,我必须面对这个问题,所以我为地图组件创建了这个问题,我在 componentDidUpdate 中使用 try-catch 处理了这个问题,因为它在组件渲染时运行了很长时间。 thanks谢谢

 componentDidUpdate() { const { map, cir1, cir2, vertical } = this._generateProps() const { center } = vertical ? this._generateProps() : this.state circle1 ? circle1.setMap(null) : null circle2 ? circle2.setMap(null) : null if (cir1) { try { circle1 = new google.maps.Circle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 0, fillColor: "#f5a623", fillOpacity: 0.35, map, center, radius: 450 }) } catch (e) { console.log(e) } } if (cir2) { try { circle2 = new google.maps.Circle({ strokeColor: "#f4ff10", strokeOpacity: 0.16, strokeWeight: 0, fillColor: "#4a90e2", fillOpacity: 0.3, map, center, radius: 800 }) } catch (e) { console.log(e) } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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