react使用Google地图

要在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密钥是安全的,并仅在服务器端或环境变量中存储,以避免在源代码中公开显示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值