我正在创建一个使用react-google-maps的web,我收到了一堆未定义的错误。我是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代码如下:
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;看起来我没能正确导入google地图,但是看看这个例子,它不应该这样做。有什么想法吗?
发布于 2019-05-03 12:49:47
你可以试试这个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)
}}
/>发布于 2018-05-27 14:30:53
你错过了lifecycle和google的导入。在示例中,您可以看到,
const { compose,withProps,生命周期}= require("recompose");
google的导入在示例中没有提到,但也应该导入。
关于导入google,它与eslint验证有关,而不是JS。执行以下更改:
PlacesAutocomplete.js第1行:
/*global google*/^这将声明eslint google是一个全局名称,并将在运行时可用。有关更多信息,请访问此git page
发布于 2020-05-27 11:10:42
我不知道为什么,但是对于Angular和React,你需要为这种库添加一个脚本标记,如下所示:
<body>
...
<script src="https://maps.googleapis.com/maps/api/js?key=<API KEY>&callback=init"
async defer></script>
</body>如果您查看内部,您可以找到window.google的定义:
window.google = window.google || {};在这种情况下,您需要使用window.google而不是this.props.google。我会尝试找到一种更好的方法来使用这个库,但这是我对这个未知问题的贡献……
https://stackoverflow.com/questions/50548632
复制相似问题