关于vue使用百度地图
引入依赖
"vue-baidu-map": "^0.21.22",
注册组件
import BaiduMap from 'vue-baidu-map';
Vue.use(BaiduMap, { ak: (Environment as any).apiKey });
注:在main.ts文件中注册全局组件,其中ak是百度开发者平台申请的 。具体可参见 百度地图开放平台,也可以参考 百度ak申请详情。
具体使用
/**
* 百度地图Api对象(用于实例化百度组件)
*
* @type {*}
* @memberof BaiduMap
*/
BMap: any;
/**
* 百度地图实例对象
*
* @type {*}
* @memberof BaiduMap
*/
map: any;
/**
* 百度地图类型
*
* @type {string}
* @memberof BaiduMap
*/
mapType:string = 'BMAP_HYBRID_MAP';
/**
* 地图加载完成
*
* @param {*} { BMap, map }
* @memberof BaiduMap
*/
mapReady({ BMap, map }: any) {
this.BMap = BMap;
this.map = map;
let point = new BMap.Point(this.lng, this.lat);
// 设置居中位置和缩放等级
map.centerAndZoom(point, 12);
// 启用滚轮缩放
map.enableScrollWheelZoom();
}
/**
* 绘制地图
*
* @return {*}
* @memberof BaiduMap
*/
render() {
return (
<baidu-map
ref='map'
class='app-baidu-map'
mapType={this.mapType}
on-ready={($event: any) => {
this.mapReady($event);
}}
>
{this.$slots.default}
</baidu-map>
);
}
注:百度地图的绘制方法
这样最基础的地图就完成啦
绘制点
let icon = new this.BMap.Icon(`${imgPath}`, new this.BMap.Size(30, 30));
// 创建Marker标注,使用自定义图标
let pt = new this.BMap.Point(item.lng, item.lat);
let marker = new this.BMap.Marker(pt, {
icon: icon,
});
// 将标注添加到地图
this.map.addOverlay(marker);
// 添加点动画
marker.setAnimation((window as any).BMAP_ANIMATION_BOUNCE);
注:
imgPath是项目存放图片的路径
item.lng、item.lat分别对应点的经度和维度
具体请参考 point参考类
效果图
绘制线
/**
* 添加折线的地图叠加层
*
* @param {[]} points
* @param {*} opts
* @memberof BaiduMap
*/
public addPolyline(points: [], opts?: any) {
if (!this.map || !this.BMap) {
return;
}
// 默认参数
const defaultOpt = {
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1,
strokeStyle: 'solid',
};
const line = new this.BMap.Polyline(points, opts || defaultOpt);
this.map.addOverlay(line);
}
注:
points是绘制点的数组,百度地图会根据数组索引依次连线
具体请参考 Polyline参考类)
效果图
绘制圈
/**
* 绘制圆覆盖物
*
* @param {*} centerPoint 中心点
* @param {number} radius 半径
* @param {*} [circleOptions] 参数
* @return {*}
* @memberof BaiduMap
*/
renderMapCircle(centerPoint: any, radius: number, circleOptions?: any) {
if (!this.map || !this.BMap) {
return;
}
// 中心圈参数
const defaultCircleOptions = {
// 圆形边线颜色
strokeColor: 'red',
// 圆形填充颜色。当参数为空时,圆形将没有填充效果
fillColor: 'red',
// 圆形边线透明度,取值范围0 - 1
strokeOpacity: 0.3,
// 圆形填充的透明度,取值范围0 - 1
fillOpacity: 0.3,
// 启用自定义编辑圆圈
enableEditing: false,
};
let circle = new this.BMap.Circle(centerPoint, radius, circleOptions || defaultCircleOptions);
this.map.addOverlay(circle);
this.curCircle = circle;
}
注:
绘制圈 需要确定一个中心点 centerPoint 以及半径 radius
enableEditing 这个参数我建议大家都传false,然后再需要改变的时候调用enableEditing()|disableEditing()
我在使用的时候发现如果绘制多个圈时,enableEditing为true会出现无法绘制的问题。
具体请参考 Circle参考类