Reactjs react-google-maps未定义
2017-08-18
4789
我正在使用 react-google-maps 包 https://github.com/tomchentw/react-google-maps 和 https://www.npmjs.com/package/react-google-maps 。我遇到一个错误,显示:
./src/App.js Line 31: 'google' is not defined no-undef Line 32: 'google' is not defined no-undef Line 37: 'google' is not defined no-undef Line 42: 'google' is not defined no-undef Line 44: 'google' is not defined no-undef
错误中我的行是:
state = {
origin: new google.maps.LatLng(41.8507300, -87.6512600),
destination: new google.maps.LatLng(41.8525800, -87.6514100),
directions: null,
}
componentDidMount() {
const DirectionsService = new google.maps.DirectionsService();
DirectionsService.route({
origin: this.state.origin,
destination: this.state.destination,
travelMode: google.maps.TravelMode.DRIVING,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
} else {
console.error(`error fetching directions ${result}`);
}
});
}
所有“google”都是错误的。
3个回答
答案是我没有将此行
/* global google */
包含到文件顶部。
Deee
2017-08-22
如果未定义
google
,则说明您未正确加载 Google Maps API。如
react-google-maps
的 README
中所述,在 React 组件代码加载
之前
,将此内容放入 HTML 中:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE"></script>
lorenzo-s
2017-08-18
您也可以只包含窗口引用来解决错误,至少使用默认的 create-react-app 配置可以解决该错误
new window.google.maps.LatLng(41.8507300, -87.6512600)
Dan
2018-02-04