首页 > 解决方案 > react-google-maps - 未捕获的 ReferenceError:未定义谷歌

问题描述

我是 ReactJS 的新手,目前我正在为一个项目使用 react-google-maps,我正在使用 FourSquare API 显示一些地方,有一个方向按钮应该显示从用户当前位置到目的地。

这是 Meeting.js

/* eslint-disable no-undef */
/* global google */
import React, { Component } from 'react';
import Map from '../../Component/Map';
import MapAPI from '../../api/GoogleMap';

class Meeting extends Component {
// constructor and other stuff...

getDirections = () => {
const DirectionsService = new google.maps.DirectionsService();

DirectionsService.route(
  {
    destination: new google.maps.LatLng(24.8861479, 67.0595196),
    origin: new google.maps.LatLng(24.8812296, 67.0727269),
    travelMode: google.maps.TravelMode.DRIVING,
  },
  (result, status) => {
    if (status === google.maps.DirectionsStatus.OK) {
      this.setState({
        directions: result,
        mapLoaded: true,
        mapVisible: true,
      });
    } else {
      alert("Sorry! Can't calculate directions!");
    }
  },
);
};

render() {
const { coords, directions, mapVisible } = this.state;

return (
  <div className="section">
    {mapVisible && (
      <Map
        coords={coords}
        dragged={this.dragged}
        isMarkerShown
        directions={directions}
        googleMapURL={MapAPI}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `350px` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    )}
  </div>
);
}
}

export default Meeting;

这是 Map.js

import React from 'react';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  DirectionsRenderer,
} from 'react-google-maps';

const Map = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultZoom={14}
      defaultCenter={{
        lat: props.coords.latitude,
        lng: props.coords.longitude,
      }}
      center={{ lat: props.coords.latitude, lng: props.coords.longitude }}
    >
      {props.isMarkerShown && (
        <Marker
          draggable={props.draggable || false}
          onDragEnd={e => props.dragged(e)}
          position={{ lat: props.coords.latitude, lng: props.coords.longitude }}
        />
      )}

      {props.directions && <DirectionsRenderer directions={props.directions} />}
    </GoogleMap>
  )),
);

export default Map;

getDirections函数在按钮上调用,它既不适用于 componentDidMount 也不适用于单击按钮,在这两种情况下我都会遇到相同的错误。

我认为这是因为谷歌的异步加载,但找不到解决这个问题的方法,我看到有人问了同样的问题,但没有令人满意的答案。任何帮助,将不胜感激。

标签: javascriptreactjs

解决方案


这是因为您导入react-google-maps了您的Map.js,并且您正在调用google您的Meeting.jsgoogle,您可以Map.js在其中使用它 - 尝试在其中使用它,您就可以开始使用了!

https://codesandbox.io/embed/nkykvozl34

更新:

包的配置react-google-maps已经更新: https ://tomchentw.github.io/react-google-maps/#usage--configuration


推荐阅读