我在我的项目中使用webpack和reactjs,现在我想集成谷歌地图api。首先,我在 package.json 文件中添加了 "react-google-maps": "^4.9.1"。下面是我的组件类。
import React, {PropTypes, Component} from 'react';
import { GoogleMap, Marker, SearchBox } from "react-google-maps";
import shouldPureComponentUpdate from 'react-pure-render/function';
const greatPlaceStyle = {
// initially any map object has left top corner at lat lng coordinates
// it's on you to set object origin to 0,0 coordinates
position: 'absolute',
width: 512,
height: 512,
left: 512 / 2,
top: 512 / 2,
border: '5px solid #f44336',
borderRadius: 512,
backgroundColor: 'white',
textAlign: 'center',
color: '#3f51b5',
fontSize: 16,
fontWeight: 'bold',
padding: 4
};
export default class SimpleMapPage extends Component {
static defaultProps = {
center: {lat: 59.938043, lng: 30.337157},
zoom: 1,
greatPlaceCoords: {lat: 59.724465, lng: 30.080121}
};
shouldComponentUpdate = shouldPureComponentUpdate;
constructor(props) {
super(props);
}
render() {
return (
<GoogleMap>
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}>
<MyGreatPlace lat={59.955413} lng={30.337844} text={'A'} />
<MyGreatPlace {...this.props.greatPlaceCoords} text={'B'} />
</GoogleMap>
);
}
}
export default class MyGreatPlace extends Component {
static propTypes = {
text: PropTypes.string
};
static defaultProps = {};
//shouldComponentUpdate = shouldPureComponentUpdate;
constructor(props) {
super(props);
}
render() {
return (
<div style={greatPlaceStyle}>
{this.props.text}
</div>
);
}
}
在我的index.html 文件中,我添加了以下JavaScript。第一个是 goold map api 依赖项。第二个是webpack打包的bundle.js。当我访问我的应用程序时,谷歌地图没有显示。我认为问题是无法在我的组件类上导入 google map api。导入 googleapis 的正确方法是什么?
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA2sDQZ-36NLlY4iMvoiuQ7mS1n-v8iq2M" async defer></script>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
最佳答案
我实现了需要两个回调成功和错误的函数,并检查谷歌是否加载。如果未加载,则开始加载使用 load-script用于将脚本节点附加到 DOM 中的元素
import loadScript from 'load-script';
const HOST = 'https://maps.googleapis.com/maps/api/js';
const KEY = 'YOUR API KEY';
const URL = `${HOST}?key=${KEY}&libraries=places`;
const loadGoogleMapApi = (
success = () => {},
error = () => {}
) => {
if (window.google) {
success();
} else {
loadScript(URL, err => {
const callback = err ? error : success;
callback();
});
}
};
export default loadGoogleMapApi;
然后我在我的 react 组件中使用了这个函数,如下所示:
initialize() {
this.api = L.map(this.map);
this.markers = L.featureGroup();
this.api.addLayer(this.markers);
loadGoogleMapApi(() => {
this.api.addLayer(new L.Google('ROADMAP'));
});
}
componentDidMount() {
this.initialize();
this.draw();
}
关于javascript - 如何在react项目中导入google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588059/