我正在使用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}`);
}
});
}
所有"谷歌"的事情都是错误。
答案是我没有将这一行/* global google */
到文件的顶部。
如果未定义google
,则说明您没有正确加载Google Maps API。正如react-google-maps
的自述文件中所述,在加载 React 组件代码之前将其放入 HTML 中:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE"></script>
您也可以只包含窗口引用来解决错误,至少在默认的创建-反应-应用程序配置中可以
new window.google.maps.LatLng(41.8507300, -87.6512600)