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

Som*_*ive 12 google-maps reactjs

我正在创建一个使用 react-google-maps 的网络,但遇到了一堆未定义的错误。我是 react/js 世界的新手,所以任何帮助都将不胜感激。这是确切的错误:

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
Run Code Online (Sandbox Code Playgroud)

这是代码:

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;
Run Code Online (Sandbox Code Playgroud)

看起来我没有正确导入谷歌地图,但看看这个例子,它不应该有。有任何想法吗?

pha*_*sal 13

你可以试试这个 new window.google.maps

这个对我有用!

例子:

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


Roh*_*ali 6

你错过了生命周期和谷歌的导入。在示例中,您可以看到,

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

并且示例中没有提到 google 的导入,但也应该导入。

关于导入 google,它与 eslint 验证有关,而不是 JS。做以下更改:

PlacesAutocomplete.js 第 1 行:

/*global google*/
Run Code Online (Sandbox Code Playgroud)

^ 这将向 eslint 声明 google 是一个全局名称,并将在运行时可用。有关更多信息,您可以浏览此git 页面