vue中使用百度地图

229 阅读1分钟

申请密钥(ak)

百度地图的官网

  • 登录百度账号,需要实名认证
  • 创建应用,选择需要的类型
  • 创建好应用就可以得到对应的ak

项目使用

  1. 下载插件 npm i vue-baidu-map --save

  2. 在文件main.js中引入

    import BaiduMap from 'vue-baidu-map';
    Vue.use(BaiduMap, {
          ak: '申请的百度地图密钥ak'
    })
    
  3. index.html入口文件添加引用

    //注意版本 v=3.0
    <script type="text/javascript" src="//api.map.baidu.com/api?v=3.0&ak=百度地图密钥ak"></script>
    
  4. 在vue文件中使用

    <template>
      <div class="controlPage">
        <baidu-map
          class="bm-view"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          @ready="handler"
        >
           //展示坐标点显示内容(标志物,icon图标自定义)
          <bm-marker
            class="bm-marker"
            v-for="(item, pos_index) in mapList"
            :key="item.id"
            :position="{ lng: item.lon, lat: item.lat }"
            @click="infoWindowOpen(pos_index)"
            :icon="{
              url: item.url,
              size: { width: 50, height: 50 },
            }"
          >
            //坐标点提示信息
            <bm-label  
              :content="item.community_name"
              :labelStyle="{ color: '#fff', fontSize: '16px', background: '',border:'none' }"
              :offset="{ width: -10, height: 50 }"
            />
             //点击坐标点展示坐标点详细信息(自定义内容)
            <bm-info-window
              class="bm-info-window"
              :show="item.isShow"
              @close="infoWindowClose(pos_index)"
            >
              <div class="warpCon">
                <div class="leftStatus" v-if="item.type == 'one'">
                  <div class="img">
                    <img
                      src="@/assets/images/talkback/index/icon-renyuan.png"
                      alt=""
                    />
                  </div>
                  <p class="status_txt">在线</p>
                </div>
                <div class="bodyCon" v-if="item.type == 'one'">
                  <div class="item">
                    <div class="lableCon">人员名称:</div>
                    <div class="item-rightCon">张xx</div>
                  </div>
                  <div class="item">
                    <div class="lableCon">定位位置:</div>
                    <div class="item-rightCon">湖北省xxx街道120号</div>
                  </div>
                </div>
                <div class="bodyCon" v-if="item.type == 'two'">
                  <div class="item">
                    <div class="lableCon">告警人员:</div>
                    <div class="item-rightCon">张xx(#123456)</div>
                  </div>
                  <div class="item">
                    <div class="lableCon">位置:</div>
                    <div class="item-rightCon">湖北省xx街道120号</div>
                  </div>
                </div>
                <div class="rightIcon">
                  <div class="img">
                    <img
                      src="@/assets/images/talkback/index/icon-renyuan.png"
                      alt=""
                    />
                  </div>
                  <div class="img">
                    <img
                      src="@/assets/images/talkback/index/icon-lujingxinxing.png"
                      alt=""
                    />
                  </div>
                </div>
              </div>
            </bm-info-window>
          </bm-marker>
        </baidu-map>
      </div>
    </template>
    <script>
    export default {
      name: "",
      data() {
        return {
          mapList: [
            {
              lon: 114.34253,
              lat: 30.49984,
              community_name: "xxx小区",
              id: 1,
              isShow: false,
              type: "one",
            },
            {
              lon: 114.343925,
              lat: 30.51379,
              community_name: "xxx",
              id: 2,
              isShow: false,
              type: "two",
            },
          ],
          center: { lng: 114.34253, lat: 30.49984 }, //经纬度
          zoom: 14, //地图展示级别
        };
      },
      created() {
        this.imgSrc(this.mapList);
         //自动缩放---自动定位中心点--展示所有点位
         let view = this.My_map.getViewport(eval(this.mapList));
         this.zoom = view.zoom;
         this.center.lng = view.center.lng;
         this.center.lat = view.center.lat;
      },
      computed: {},
      methods: {
        handler({ BMap, map }) {
          map.addControl(new BMap.NavigationControl());
          //添加地图类型控件
          map.addControl(new BMap.MapTypeControl());
          //styleId:自己配置的地图样式 发布一下生成styleId,直接使用
          map.setMapStyleV2({
            styleId: "09723701fbd5c73dffe6eb0f3de8e980",
          });
        },
        //点击展开
        infoWindowOpen(pos) {
          this.mapList[pos].isShow = true;
        },
         //点击关闭
        infoWindowClose(pos) {
          this.mapList[pos].isShow = false;
        },
        //自定义坐标点图标
        imgSrc(items) {
          items.forEach((v) => {
            let path = "";
            switch (v.type) {
              case "one":
                path = require("@/assets/images/talkback/index/dingwei-icon-zaixian.png");
                break;
              case "two":
                path = require("@/assets/images/talkback/index/dingwei-sos-1.png");
                break;
              default:
                break;
            }
            v.url = path;
          });
        },
      },
    };
    </script>
    <style lang='scss' scoped>
    .controlPage {
      width: 100%;
      height: 100%;
      ::v-deep .bm-view {
        width: 100%;
        height: 100%;
        
        //隐藏地图控件
        .anchorTL {
          display: none;
        }
        .anchorTR {
          display: none;
        }
        .anchorBL {
          display: none;
        }
        
        .warpCon {
          display: flex;
          justify-content: space-between;
          width: 440px;
          height: 150px;
          font-size: 12px;
          color: #ffffff;
          background: #193f40;
          border-radius: 2px;
          padding: 25px 12px;
          .leftStatus {
            width: 40px;
            margin-right: 10px;
            .img {
              width: 100%;
              margin-bottom: 10px;
              img {
                width: 100%;
                height: 40px;
              }
            }
            .status_txt {
              color: #6fcf97;
              text-align: center;
            }
          }
          .bodyCon {
            .item {
              display: flex;
              justify-content: start;
              margin-bottom: 9px;
              .lableCon {
                min-width: 80px;
                text-align: left;
                color: rgba(255, 255, 255, 0.5);
                margin-right: 12px;
              }
            }
          }
          .rightIcon {
            height: 100%;
            padding-top: 6px;
            .img {
              width: 36px;
              height: 36px;
              margin-bottom: 12px;
              img {
                width: 100%;
                height: 100%;
              }
            }
          }
        }
      }
    }
    </style><style>/*地图标题 infoWindow*/
    .BMap_bubble_title{
      color:#fff;
      font-size:18px;
      /*font-weight: bold;*/
      text-align:left;
      background:transparent !important;
    }
    ​
    .BMap_pop .BMap_top{
      background:#193F40 !important;
      border:0 !important;
    }
    .BMap_pop .BMap_center{
      /* width:251px !important; */
      border:0 !important;
      background:#193F40 !important;
    }
    .BMap_pop .BMap_bottom{
      border:0 !important;
      background:#193F40 !important;
    }
    ​
    .BMap_pop div:nth-child(3){
      background:transparent !important;
    }
    .BMap_pop div:nth-child(3) div{
      border-radius:7px;
      background:#193F40 !important;
      border:0 !important;
    }
    .BMap_pop div:nth-child(1){
      border-radius:7px 0 0 0;
      background:transparent !important;
      border:0 !important;
    }
    .BMap_pop div:nth-child(1) div{
      background:#193F40 !important;
    }
    .BMap_pop div:nth-child(5){
      border-radius:0 0 0 7px;
      background:transparent !important;
      border:0 !important;
    }
    .BMap_pop div:nth-child(5) div{
      border-radius:7px;
      background:#193F40 !important;
    }
    .BMap_pop div:nth-child(7){
      background:transparent !important;
    }
    .BMap_pop div:nth-child(7) div{
      border-radius:7px;
      background:#193F40 !important;
    }
    ​
    /* 小箭头隐藏 */
    .BMap_pop div:nth-child(8){
      background:#193F40 !important;
      height: 0 !important;
    }
    /*窗体阴影*/
    .BMap_shadow div:nth-child(5) img{
      /* margin-left: -1100px !important; */
    }
    ​
    .BMap_shadow div:nth-child(4){
      /* width: 262px !important; */
    }
    .BMap_shadow div:nth-child(9){
       /* display: none;  */
    }
    ​
    /*下面箭头替换为自己本地修改过的*/
    /* img[src="http://api0.map.bdimg.com/images/iw3.png"] {
      content: url('../img/Screen/arrow.png');
    }
    img[src="https://api.map.baidu.com/images/iw3.png"] {
      margin-top: -692px !important;
      filter: alpha(opacity=70);
      content: url('../img/Screen/arrow.png');
    } */
    </style>
    ​
    ​
    ​
    

    根据地址或者经纬度定位点

<template>
  <div class="maskLayer" v-if="showSelectAddress">
    <div class="hintLayer dialogCon">
      <div class="dcTitle">
        <p class="title">{{ hintTitle }}</p>
        <p class="close" v-on:click="handleCloseLayer">
          <img src="@/assets/images/public/icon-guanbi-tank.png" />
        </p>
      </div>
      <div class="hlCon">
       //地图组件
        <baidu-map
          class="bm-view"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          @click="selectPoint"
          @ready="handler"
        >
        //位置搜索功能
          <bm-local-search
            :keyword="searchWord"
            :panel="false"
            :auto-viewport="true"
            @searchcomplete="searchcomplete"
          ></bm-local-search>
          <bm-marker
            :position="point"
            :icon="{
              url: require('@/assets/images/public/map_dingwei.png'),
              size: { width: 50, height: 50 },
            }"
          >
          </bm-marker>
        </baidu-map>
    //位置搜索框
        <div class="searchArea">
          <div class="warp">
            <el-input
              type="text"
              placeholder="点击鼠标获取详细位置"
              v-model="keyword"
            ></el-input>
            <div class="btnSearch" @click="setPlace">
              <img src="@/assets/images/public/map_search.png" alt="" />
            </div>
          </div>
          <!-- <div class="sign">标记区域位置</div> -->
        </div>
      </div>
      <div class="dcBottom">
        <p class="item" v-on:click="handleHintInfo">确定</p>
        <p class="item" v-on:click="handleCloseLayer">取消</p>
      </div>
    </div>
  </div>
</template> 
​
<script>
export default {
  data() {
    return {
      addressInfo: {},
      keyword: "",
      searchWord: "",
      communitList: [],
      center: {}, //经纬度
      point: {}, //经纬度
      zoom: 14, //地图展示级别
      BAddress: "",
      BMap: {},
      map: {},
      my_map: {
        labelStyle: {
          color: "#fff",
          fontSize: "20px",
          background: "",
          border: 0,
        },
      },
    };
  },
  props: {
    hintTitle: {
      type: String,
      default: "地图选点",
    },
    addressStr: {
      type: String,
      default: null,
    },
    showSelectAddress: {
      type: Boolean,
      default: false,
    },
    saveItemInfo: {
      type: Object,
      default: null,
    },
  },
​
  methods: {
    handler({ BMap, map }) {
      let that = this;
      map.addControl(new BMap.NavigationControl());
      //添加地图类型控件
      map.addControl(new BMap.MapTypeControl());
      map.setMapStyleV2({
        styleId: "09723701fbd5c73dffe6eb0f3de8e980",
      });
      that.BMap = BMap;
      that.map = map;
​
      // 获取自动定位方法
      var geolocation = new BMap.Geolocation();
      // 获取逆解析方法实例
      this.myGeo = new BMap.Geocoder();
      // 获取自动定位获取的坐标信息
      geolocation.getCurrentPosition(
        function (r) {
          if (r != null) {
            this.center = {
              lng: r.point.lng,
              lat: r.point.lat,
            };
            this.point = {
              lng: r.point.lng,
              lat: r.point.lat,
            };
          }
        },
        { enableHighAccuracy: true }
      );
    },
    searchcomplete(e) {
      let that = this
      try {
        if (e.Ir && e.Ir.length > 0) {
          that.center = e.Ir[0].point;
          that.point = e.Ir[0].point;
          //自动缩放---自动定位中心点
          let view = that.map.getViewport(eval([e.Ir[0].point]));
          that.zoom = view.zoom;
          that.center = view.center;
          that.point = view.center;
        }
      } catch (error) {
        console.log(error);
      }
    },
    selectPoint({ point }) {
      let that = this;
      that.searchWord = "";
      that.point = point;
      that.center = point;
      //自动缩放---自动定位中心点
      let view = that.map.getViewport(eval([point]));
      that.zoom = view.zoom;
      that.center = view.center;
      that.point = view.center;
      // 根据坐标逆解析获取地址详细描述
      that.myGeo.getLocation(point, function (result) {
        if (result) {
          that.addressInfo = result;
          that.BAddress =
            result.surroundingPois.length > 0
              ? result.surroundingPois[0].address +
                result.surroundingPois[0].title
              : result.address;
          that.keyword = that.BAddress;
          //把得到的详细地址的信息回显给用户
        }
      });
    },
​
    setPlace() {
      this.searchWord = this.keyword;
    },
   //提交地址
    handleHintInfo() {
      if (this.BAddress == "") {
        this.BAddress = this.keyword;
      }
      this.$emit("getAddress", this.BAddress, this.addressInfo);
      this.$emit("update:showSelectAddress", false);
    },
    handleCloseLayer() {
      this.$emit("update:showSelectAddress", false);
    },
  },
  created() {
    //编辑--定位地址回显定位
    this.keyword =
      this.saveItemInfo.address != "" ? this.saveItemInfo.address : "";
    if (this.saveItemInfo.lon != null && this.saveItemInfo.lon != "") {
      this.center.lng = this.saveItemInfo.lon;
      this.center.lat = this.saveItemInfo.lat;
      this.point.lng = this.saveItemInfo.lon;
      this.point.lat = this.saveItemInfo.lat;
    } else {
      if(this.keyword!=""&&this.keyword!=undefined) {
        this.searchWord = this.keyword
      }else {
        this.$message.error("定位地址为空");
      }
    }
  },
  mounted() {},
};
</script>
​
​