Vue 百度地图的两种使用方式并且动态添加标注

第一种使用  vue-baidu-map 的方法

首先 npm install vue-baidu-map  --save
1 全局引入
在main.js 里面引入
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {ak:'2Zvw46SfEejaTIckyE8SwSWxcUkALsxi'}); ak是百度地图秘钥
2 局部引入 (推介使用性能消耗小,局部引入直接把上面的全部注释,然后在html添加ak)
import { BaiduMapBmScaleBmGeolocationBmMarkerBmLabelBmInfoWindow } from 'vue-baidu-map'
export default {
  name: "teamCheckWork",
   components: {
    BaiduMap,
    BmScale,
    BmGeolocation,
    BmMarker,
    BmLabel,
    BmInfoWindow
   },
  data() {
    return {
      signedIn:[],   // 已签到数据
      onSignedIn:[], // 未签到数据
 
      map_center:{lng:0,lat:0}, // 初始化中心点位置
      map_zoom:15, // 初始化地图缩放大小这两个必须有
    };
  },
}}}}}// 地图初始化
    handler({ BMapmap }) {
        console.log(BMapmap);
        let _this = this  //设置一个临时变量指向vue实例,因为在百度地图回调里使用this,指向的不是vue实例
        this.BMap = BMap
        this.map = map
        console.log(this.map);
        // 刚进入页面中的定位,需要向用户授权
        let geolocation = new BMap.Geolocation();
        let gc = new BMap.Geocoder();
        // console.log(geolocation,gc);
        // 获取当前的地理位置
        geolocation.getCurrentPositionfunction(r{
            // if(this.getStatus() == BMAP_STATUS_SUCCESS) {
            var pt = r.point;
            gc.getLocation(ptfunction(rs){
                var addComp = rs.addressComponents;
                _this.addrPoint.address= addComp.province + addComp.city + addComp.district + addComp.street+addComp.streetNumber;
            });
            console.log('r.point.lat',r.point.lng,r.point.lat)
            this.map_center = r.point
            console.logthis.map_center);
            _this.addrPoint.lng = r.point.lng;
            _this.addrPoint.lat = r.point.lat;
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);
            map.panTo(r.point);
            _this.getTeamSignIn(this.nowTime);
            if(r.accuracy==null){
                // alert('accuracy null:'+r.accuracy);
            //用户决绝地理位置授权
            return;
            }
            // }else{
            //  alert('failed'+this.getStatus());
            // }
        },{enableHighAccuracy: true});

    },
// 获取团队考勤记录
      getTeamSignIn(time){
          let that=this;
          this.$http.get("/attendance/getTeamAttendance?attendanceTime=" + time).then(res => {
            console.log('res',res);
            this.getTeamSignInHistory= res;
            // console.log(this.getTeamSignInHistory);
            if(this.getTeamSignInHistory.length>0){
                console.log('aaaaaa');
                this.getTeamSignInHistory.forEach((item,index)=>{
                    item.status? this.signedIn.push(item): this.onSignedIn.push(item);
                });
//
                this.signedIn=[ /模拟数据获取直接按照格式赋值就会在地图上显示出点 :position="{lng:item.SignInLongitude, lat:item.SignInLatitude}" v-for="(item,index) in signedIn"
                    {
                        EmployeeName:'张一',
                        SignInAddress:'大剧院',
                        SignInLatitude: '38.465846',
                        SignInLongitude: '112.736636',
                        SignInTime:'2020-9-29',
                        status:1,
                        userid:'26b6c76b-4cf9-4416-ae92-b4268b9f9185'
                    },
                    {
                        EmployeeName:'张二',
                        SignInAddress:'海底',
                        SignInLatitude: '38.454601',
                        SignInLongitude: '112.730671',
                        SignInTime:'2020-9-29',
                        status:1,
                        userid:'26b6c76b-4cf9-4416-ae92-b4268b9f9185'
                    },
                    {
                        EmployeeName:'张三',
                        SignInAddress:'南城',
                        SignInLatitude: '38.449515',
                        SignInLongitude: '112.728228',
                        SignInTime:'2020-9-29',
                        status:1,
                        userid:'26b6c76b-4cf9-4416-ae92-b4268b9f9185'
                    }
                ],
                console.log('signedIn',this.signedIn);
                console.log(this.map);
                // this.signedIn.forEach((items,index)=>{
                //     console.log(items);
                //     //把获取回来的点添加到地图上
                //     console.log(that.map);
                //     // console.log(window)
                //     var points = new BMap.Point(items.SignInLongitude,items.SignInLatitude);//创建坐标点
                //     var label = new BMap.Label(items.EmployeeName,{
                //         offset:new BMap.Size(25,5)
                //     });
                //     // var opts = {
                //     //     250,
                //     //     height: 100,
                //     //     title:item.EmployeeName
                //     // };
                //     // var infoWindows = new BMap.InfoWindow(item.EmployeeName,opts);
                //     // markerFun(points,label,infoWindows);
                //     this.addMarker(points,label);
                // });

              }else{
                  this.$toast("当前时间还未有人提交考勤记录");
              }
          }) .catch(err => {

              this.$toast(err);
          });
      }
 
html》
<baidu-map class="map map-content" :center="map_center" :zoom="map_zoom" @ready="handler" :style="{height:height}" :double-click-zoom="false" ak="2Zvw46SfEejaTIckyE8SwSWxcUkALsxi">
      <bm-marker :position="{lng:item.SignInLongitude, lat:item.SignInLatitude}"  v-for="(item,index) in signedIn" :key="index" animation="BMAP_ANIMATION_BOUNCE">
         <bm-label :content="item.EmployeeName" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{ -35, height: 30}"/>
      </bm-marker>
  </baidu-map>

第二种直接引用百度地图
 1这种只有一种引用方式直接在哪里用就在哪里引用
  html
<div  class="map-content"id="map-container" :style="{height:height}"></div>
注意:一定要加高度不然会不显示
 async mounted() {
    await MP('2Zvw46SfEejaTIckyE8SwSWxcUkALsxi') //加载引入地图,参数是秘钥
    this.initMap();
  },
 // 初始化地图获取当前定位点
    initMap() {
        var that = this;
      // 刚进入页面中的定位,需要向用户授权
      let geolocation = new BMap.Geolocation();
      let gc = new BMap.Geocoder();
      // console.log(geolocation,gc);
      // 获取当前的地理位置
      geolocation.getCurrentPosition( function(r) {
        // if(this.getStatus() == BMAP_STATUS_SUCCESS) {
          var pt = r.point;
          gc.getLocation(pt, function(rs){
              var addComp = rs.addressComponents;
              that.addrPoint.address= addComp.province + addComp.city + addComp.district + addComp.street+addComp.streetNumber;
          });
        // console.log('r.point.lat',r.point.lng,r.point.lat)
        that.addrPoint.lng = r.point.lng;
        that.addrPoint.lat = r.point.lat;
        that.generatingMaps(r.point)
        if(r.accuracy==null){
            // alert('accuracy null:'+r.accuracy);
          //用户决绝地理位置授权
          return;
        }
        // }else{
        //  alert('failed'+this.getStatus());
        // }
      },{enableHighAccuracy: true});

    },

    //  生成当前位置的地图并添加初始化点
    generatingMaps(value){
      var map = new BMap.Map("map-container", {enableMapClick:false,minZoom:15,maxZoom:20})  //新建地图实例,enableMapClick:false :禁用地图默认点击弹框,minZoom地图最大最小实例
      var point = new BMap.Point( value.lng,value.lat);
      map.centerAndZoom(point,17);
      let marker = new BMap.Marker(new BMap.Point( value.lng,value.lat)); // 创建点
      map.addOverlay(marker);
    },
// 获取数据
      getTeamSignIn(time){
          this.$http.get("/attendance/getTeamAttendance?attendanceTime=" + time).then(res => {
            console.log('res',res);
            this.getTeamSignInHistory= res;
            // console.log(this.getTeamSignInHistory);
            if(this.getTeamSignInHistory.length>0){
                console.log('aaaaaa');
                this.getTeamSignInHistory.forEach((item,index)=>{
                    item.status? this.signedIn.push(item): this.onSignedIn.push(item);
                });
                this.signedIn=[
                    {
                        EmployeeName:'张一',
                        SignInAddress:'大剧院',
                        SignInLatitude: '38.465846',
                        SignInLongitude: '112.736636',
                        SignInTime:'2020-9-29',
                        status:1,
                        userid:'26b6c76b-4cf9-4416-ae92-b4268b9f9185'
                    },
                    {
                        EmployeeName:'张二',
                        SignInAddress:'海底',
                        SignInLatitude: '38.454601',
                        SignInLongitude: '112.730671',
                        SignInTime:'2020-9-29',
                        status:1,
                        userid:'26b6c76b-4cf9-4416-ae92-b4268b9f9185'
                    },
                    {
                        EmployeeName:'张三',
                        SignInAddress:'南城',
                        SignInLatitude: '38.449515',
                        SignInLongitude: '112.728228',
                        SignInTime:'2020-9-29',
                        status:1,
                        userid:'26b6c76b-4cf9-4416-ae92-b4268b9f9185'
                    }
                ],
                console.log('signedIn',this.signedIn);
                console.log(this.map);
                this.signedIn.forEach((items,index)=>{
                    console.log(items);
                    //把获取回来的点添加到地图上
                    console.log(that.map);
                    // console.log(window)
                    var points = new BMap.Point(items.SignInLongitude,items.SignInLatitude);//创建坐标点
                    var label = new BMap.Label(items.EmployeeName,{
                        offset:new BMap.Size(25,5)
                    });
                    // var opts = {
                    //     250,
                    //     height: 100,
                    //     title:item.EmployeeName
                    // };
                    // var infoWindows = new BMap.InfoWindow(item.EmployeeName,opts);
                    // markerFun(points,label,infoWindows);
                    this.addMarker(points,label);
                });

              }else{
                  this.$toast("当前时间还未有人提交考勤记录");
              }
          }) .catch(err => {

              this.$toast(err);
          });
      }
    // 调用添加多个标注
    addMarker(points,label){
        let that=this; // 注意this指向问题指向map
        console.log(points,label);
        var markers = new BMap.Marker(points);
        that.map.addOverlay(markers);
        markers.setLabel(label);
        // markers.addEventListener("click",function (event) {
        //     console.log("0001");
        //     map.openInfoWindow(infoWindows,points);//参数:窗口、点  根据点击的点出现对应的窗口
        // });
    },

  

 
  <baidu-map class="map map-content" :center="map_center" :zoom="map_zoom" @ready="handler" :style="{height:height}" :double-click-zoom="false" ak="2Zvw46SfEejaTIckyE8SwSWxcUkALsxi">
                <bm-marker :position="{lng:item.SignInLongitude, lat:item.SignInLatitude}"  v-for="(item,indexin signedIn" :key="index" animation="BMAP_ANIMATION_BOUNCE">
                    <bm-label :content="item.EmployeeName" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{ -35, height: 30}"/>
                </bm-marker>
            </baidu-map>
原文地址:https://www.cnblogs.com/zxbky/p/13772198.html