【发布时间】:2018-07-07 17:13:24
【问题描述】:
我正在尝试在 React 组件中使用 Google 地图,但它似乎不起作用。 我目前指的是https://developers.google.com/maps/documentation/javascript/adding-a-google-map
这是我的组件的代码:
class ContactBody extends React.Component {
componentWillMount() {
const script = document.createElement("script");
const API = 'AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw';
script.src = `https://maps.googleapis.com/maps/api/js?key=${API}&callback=initMap`;
script.async = true;
document.body.appendChild(script);
};
initMap() {
const uluru = {lat: -25.363, lng: 131.044};
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
const marker = new google.maps.Marker({
position: uluru,
map: map
});
}
render() {
this.initMap();
return (
<div>
<h1>Contact</h1>
<div id="map" style={{width: 400, height: 300}}></div>
</div>
)
}
}
ReactDOM.render(
<ContactBody />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>
但是,当我运行它时,我收到“Uncaught ReferenceError: google is not defined”
谁能告诉我我的代码有什么问题?
谢谢。
【问题讨论】:
-
您是否已将
https://maps.googleapis.com/maps/api/js?key=${API}&callback=initMap;添加到您的index.html文件中?
标签: javascript reactjs google-maps redux google-maps-markers