一、在react项目中引入百度地图
1.首先依旧是百度地图首页
百度地图开放平台 | 百度地图API SDK | 地图开发
https://lbsyun.baidu.com/
2.找到开发文档中react开发:
React-BMapGL文档
https://lbsyun.baidu.com/solutions/reactBmapDoc
3.开始使用安装地图
引入脚本
首先,需要在你的public/index.html模板页面头部加载百度地图JavaScript API代码,
密钥可去百度地图开放平台官网申请
<script type="text/javascript" src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=您的密钥"></script>
然后,使用npm或者yarn方式安装react组件库,然后通过es模块加载
npm install react-bmapgl --save
yarn add react-bmapgl --save
4.在react中写入地图
import React from 'react';
import { Map, Marker, NavigationControl, InfoWindow } from 'react-bmapgl';
export default function Index() {
return (
<div>
<Map center={{ lng: 116.402544, lat: 39.928216 }} zoom="11">
<Marker position={{ lng: 116.402544, lat: 39.928216 }} />
<NavigationControl />
<InfoWindow position={{ lng: 116.402544, lat: 39.928216 }} text="北京市" title="地标" />
</Map>
</div>
)
}
5.启动项目就能看到引入的地图了。
二、在umi中引入百度地图
1.在src/pages下创建一个plugin/customPlugin.js文件
customPlugin.js 文件代码如下
export default (api, opts) => {
// 在HTML尾部添加脚本
api.addHTMLScripts(() => {
return [
{
// 百度地图
type:"text/javascript",
src:"//api.map.baidu.com/api?type=webgl&v=1.0&ak=您的密钥"
}
]
})
}
2.在umirc.ts中导入本地新建的插件文件customPlugin.js
/**
* umirc.ts,umi项目默认配置文件
*/
import { defineConfig } from 'umi';
export default defineConfig({
nodeModulesTransform: {...},
dva: {},
routes: [...],
fastRefresh: {},
plugins: ['./src/pages/plugins/customPlugin.js'] //添加一个plugins插件
});
3.使用npm
方式安装react
组件库,然后通过es
模块加载
npm install react-bmapgl --save
4.在文件中写入地图
import { Map } from 'react-bmapgl'
function Index() {
return (
<div>
<Map
style={{ height: 1200 }}
center={new BMapGL.Point(116.404449, 39.914889)}
zoom={12}
heading={0}
tilt={40}
onClick={(e: any) => console.log(e)}
enableScrollWheelZoom
/>
</div>
)
}
export default Index
5.启动项目就能看到地图效果了。