vue 使用百度地图(vue-baidu-map)
官网: https://dafrok.github.io/vue-baidu-map/#/zh/index
- 安装
npm install vue-baidu-map --save
- main.js引入
import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
ak: 'MGN1E7IAI7hIiIDNoTvctiCUDANfFXBp'
})
- 使用
<template>
<!-- 地图 -->
<div>
<baidu-map class="bm-view" :zoom="zoom" :center="center" inertial-dragging @ready="mapReady" :scroll-wheel-zoom="true" @click="handleMapClick">
<!-- 地图类型切换 -->
<bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
<!-- 缩放控件 anchor代表控件停靠位置 anchor="BMAP_ANCHOR_TOP_RIGHT"代表放在右上角-->
<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
<!-- 自定义点位 -->
<bm-marker :position="startPoint" :rotation="0" :icon="{ url: require('@/assets/logo.png'), size: { width: 60, height: 28 } }" />
<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
<!-- 行政区划 -->
<bm-boundary name="北京市丰台区" :strokeWeight="2" strokeColor="blue"></bm-boundary>
</baidu-map>
</div>
</template>
<script>
import { BaiduMap, BmControl, BmView, BmAutoComplete, BmLocalSearch, BmMarker, BmGeolocation, BmlLushu } from "vue-baidu-map";
export default {
components: {
BaiduMap,
BmControl,
BmView,
BmAutoComplete,
BmLocalSearch,
BmMarker,
BmGeolocation,
BmlLushu,
},
data() {
return {
//定位位置信息
center: {
lng: 116.404,
lat: 39.915,
},
zoom: 15,
polylinePath: [
{ lng: 116.404, lat: 39.915 },
{ lng: 116.405, lat: 39.92 },
{ lng: 116.423493, lat: 39.907445 },
],
startPoint: { lng: 116.404, lat: 39.915 },
};
},
methods: {
//地图加载后的回调
mapReady({ BMap, map }) {
console.log(BMap, map);
const that = this;
var geolocation = new BMap.Geolocation();
// 获取自动定位获取的坐标信息
geolocation.getCurrentPosition(
function (r) {
that.center = {
lng: r.point.lng,
lat: r.point.lat,
};
},
{ enableHighAccuracy: true }
);
},
// 地图点击获取经纬度
handleMapClick(e) {
this.zoom = e.target.getZoom();
// 创建地址解析器的实例
let geocoder = new BMap.Geocoder();
geocoder.getLocation(e.point, rs => {
console.log(e.point.lng, e.point.lat);
});
},
},
};
</script>
<style scoped>
/* 给个宽高 */
.bm-view {
height: 70vh;
margin-top: 20px;
width: 100%;
}
/* 去除百度地图的图标 根据实际情况看是否要加样式穿透(::v-deep) */
::v-deep .anchorBL {
display: none !important;
}
</style>