javascript - 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 也不适用于单击按钮,在这两种情况下我都会遇到相同的错误。
我认为这是因为谷歌的异步加载,但找不到解决这个问题的方法,我看到有人问了同样的问题,但没有令人满意的答案。任何帮助,将不胜感激。
解决方案
这是因为您导入react-google-maps
了您的Map.js
,并且您正在调用google
您的Meeting.js
google,您可以Map.js
在其中使用它 - 尝试在其中使用它,您就可以开始使用了!
https://codesandbox.io/embed/nkykvozl34
更新:
包的配置react-google-maps
已经更新:
https ://tomchentw.github.io/react-google-maps/#usage--configuration
推荐阅读
- flutter - Firebase 存储 url 私有访问
- java - 尝试运行 appium 但应用程序自动关闭并显示错误
- python-3.x - 蟒蛇:任务得到了不好的收益:
- docker - 无法让 PostGis 图像改为用作本地文件
- java - 在 xml 的响应正文中删除 <
- css - 如何修复 react-datepicker 总是移到下一行并将其他人推到下一行
- reactjs - 警告:测试中对 Formik 的更新未包含在 act(...) 中
- apache-spark - pyspark - 将 epoc 时间转换为日期
- amazon-web-services - 无法创建连接 AWS API Gateway - VPC
- android - 不能使用自定义选择文本