前言
本章我们将通过react+typescript的方式给项目接入百度地图
步骤一:注册百度开发者,获取密匙
百度地图开放平台注册成为开发者,进入控制台,创建应用获取AK密钥
步骤二:修改项目的index.html
贴入如下代码
<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=你的ak密钥"></script>
步骤三:修改webpack.config.js
添加如下代码
// 外部因素,百度地图
externals:{
'BMap':'BMap',
}
步骤四:项目中使用百度地图的api
以定位和逆地址解析为例
- 封装getBaiduLocationApi方法
import { Toast } from 'antd-mobile';
// 获取百度地图定位
export const getBaiduLocationApi = () => {
const promiseItem = new Promise((resolve, reject) => {
// 引入百度地图
const BMap = require('BMap');
const geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition((r: any) => {
if(geolocation.getStatus() === 0){
// 获取经纬度
console.log('您的位置:'+r.point.lng+','+r.point.lat);
const point = new BMap.Point(r.point.lng,r.point.lat);
const geoc = new BMap.Geocoder();
// 获取逆地址解析
geoc.getLocation(point,(rs: any) => {
const addComp = rs.addressComponents;
console.log(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber);
const res = {
longitude: r.point.lng,
latitude: r.point.lat,
province: addComp.province,
city: addComp.city,
district: addComp.district,
street: addComp.street,
streetNumber: addComp.streetNumber,
}
resolve(res)
});
} else {
// console.log('定位失败');
Toast.fail('定位失败,请检查是否开启手机定位功能');
reject('定位失败');
}
},{enableHighAccuracy: true});
})
return promiseItem;
}
- react组件中调用
import React, { Component } from 'react';
import { getBaiduLocationApi } from '../../utils/common';
import { Toast } from 'antd-mobile';
type StateType = {
longitude: string | null;
latitude: string | null;
};
type PropType = {
[propName: string]: any;
};
interface PersonalInfo {
state: StateType;
props: PropType;
}
class PersonalInfo extends Component {
constructor(props: any) {
super(props);
this.state = {
longitude: null,
latitude: null,
}
}
componentDidMount() {
this.getLocation();
}
// 获取定位
private getLocation = async () => {
const res: any = await getBaiduLocationApi();
this.setState({
longitude: res.longitude,
latitude: res.latitude,
})
}
render() {
return ()
)
}
}
export default PersonalInfo;
文章参考:https://blog.csdn.net/weixin_39742727/article/details/111136050