1.第一步要加入项目package.json中或者直接yarn install它都可以
"@react-google-maps/api": "^2.19.3",
2.加入项目中
import AMapLoader from '@amap/amap-jsapi-loader';
import React, { PureComponent } from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';
interface ScalSelectStates {
/**
* 当前选择位置经纬度
*/
centerPosition: any[];
}
export class ScalSelect extends PureComponent<{}, ScalSelectStates> {
constructor(props: any) {
super(props);
this.state = {
centerPosition: [116.409969,39.982387],
};
}
//谷歌地图点击方法
handleGoogleClick = (event: any) => {
if (event && event.latLng) {
const centerPosition = [event.latLng.lng().toFixed(6), event.latLng.lat().toFixed(6)];
this.setState({
centerPosition,
});
}
};
render() {
const {centerPosition} = this.state;
const lng = Number(centerPosition[0]);
const lat = Number(centerPosition[1]);
const googleKey = ''; //申请的谷歌key
return (
<div style={{ height: '400px', width: '100%' }}>
<LoadScript googleMapsApiKey={googleKey}>
<GoogleMap
mapContainerStyle={{ width: '100%', height: '400px' }}
zoom={11}
center={{ lat, lng }}
onClick={this.handleGoogleClick}
>
<Marker position={{ lat, lng }} />
</GoogleMap>
</LoadScript>
</div>
)
}
}
附上效果图一张
希望对大家有帮助~❤️