要在Create React App项目中使用谷歌地图,需要进行以下步骤:
1. **获取Google Maps API密钥:** 首先,需要获得一个Google Maps API密钥。访问https://console.cloud.google.com,创建一个新的项目(如果还没有创建)并启用"Maps JavaScript API"。然后,生成一个API密钥。
2. **在React项目中安装`google-maps-react`库:** 使用以下命令安装`google-maps-react`库,它是一个用于在React中使用Google地图的库:
npm install google-maps-react --save
3. **在React组件中使用Google地图:** 创建一个React组件,然后在组件中引入`google-maps-react`库,使用您的Google Maps API密钥来显示地图。以下是一个简单的示例:
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
class MapContainer extends Component {
render() {
const mapStyles = {
width: '100%',
height: '400px',
};
return (
<Map
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={{
lat: 37.7749, // 纬度
lng: -122.4194, // 经度
}}
>
<Marker position={{ lat: 37.7749, lng: -122.4194 }} />
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: 'YOUR_GOOGLE_MAPS_API_KEY_HERE', // 替换为您的API密钥
})(MapContainer);
请确保替换代码中的`YOUR_GOOGLE_MAPS_API_KEY_HERE`为自己的Google Maps API密钥。
4. **在项目中使用`MapContainer`组件:** 在你的应用程序中导入并使用`MapContainer`组件,将其添加到页面上的任何位置。
import React from 'react';
import './App.css';
import MapContainer from './MapContainer';
function App() {
return (
<div className="App">
<h1>Google 地图示例</h1>
<MapContainer />
</div>
);
}
export default App;
5. 最后,启动React应用程序:
npm start
请确保Google Maps API密钥是安全的,并仅在服务器端或环境变量中存储,以避免在源代码中公开显示。