一、安装和引入 vue-baidu-map-3x
先附上官方文档地址:vue-baidu-map-3x
npm install vue-baidu-map-3x --save
二、在你的 Vue 项目中全局或局部引入
main.js
// 引入百度地图
import BaiduMap from 'vue-baidu-map-3x'
app.use(BaiduMap, {
ak: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' // 替换为你的百度地图 API 密钥
})
三、在组件中使用
注意:地图需要设置高度才能展示、必须设置高度!
map.vue
<template>
<baidu-map
class="bm-view"
:center="localCenter"
:zoom="zoom"
:scroll-wheel-zoom="true"
@ready="init"
>
</baidu-map>
</template>
<script setup>
let localCenter = ref({ lng: 120.33219001501008, lat: 36.10803201844253 });
const zoom = ref(14);
const init = async ({ map }) => {
// 创建导航控件
const navigationControl = new BMap.NavigationControl({
type: BMAP_NAVIGATION_CONTROL_LARGE, // 设置为标准的平移缩放控件(包括平移、缩放按钮和滑块)
enableGeolocation: true, // 启用定位
});
const MapTypeControlType = new BMap.MapTypeControl({
mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],//配置地图类型(BMAP_NORMAL_MAP:普通、BMAP_HYBRID_MAP:混合)
});
// 添加控件到地图
map.addControl(navigationControl);
map.addControl(MapTypeControlType);
};
</script>
<style scoped lang="scss">
.bm-view {
width: 100%;
height: 100%;
}
</style>
四、其他功能
1、比例尺
<!-- 比例尺 -->
<bm-scale anchor="BMAP_ANCHOR_BOTTOM_LEFT"></bm-scale>
2、地图显示定位点
<bm-marker
v-for="(device, index) in deviceListData"
:key="index"
:position="{ lng: device.lon, lat: device.lat }"
>
</bm-marker>
3、信息窗(注意信息窗只能存在一个 不要写在for循环里面)
<bm-info-window :show="show" @close="infoWindowClose" @open="infoWindowOpen">我爱北京天安门</bm-info-window>
4、由多个点组成的轨迹连线
<bm-polyline
:path="trackingData"
stroke-color="red"
stroke-opacity="0.7"
stroke-weight="2"
></bm-polyline>
5、添加地图类型切换组件(普通街道视图、卫星视图、透视图像视图、卫星和路网的混合视图)(开始的代码里面已经包含了 )
在init方法里面添加:
const MapTypeControlType = new BMap.MapTypeControl({
mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
});
map.addControl(MapTypeControlType);
6、添加缩放控件(开始的代码里面已经包含了 )
const navigationControl = new BMap.NavigationControl({
type: BMAP_NAVIGATION_CONTROL_LARGE, // 设置为标准的平移缩放控件(包括平移、缩放按钮和滑块)
enableGeolocation: true, // 启用定位
});
map.addControl(navigationControl);