1- 安装 yarn add vue-baidu-map-v3
2-引入 注册 main.js 文件

import BaiduMap from "vue-baidu-map-v3";
Vue.use(BaiduMap, {
  ak: "XA5932348T9SXZZZtZZZVtRNWexL11111111111111JSOd2e27AAHzVAAAuSt4bP999Swpmf7",
});

3- public下的index.html 文件
在这里插入图片描述
4- 解决 跨域问题 (目前项目中使用的是 第一种方案,开发环境中可以,线上环境的话需要后台配合改下 代理配置)
第一种方案:4.1 src下的api 新建 baidu.js 文件
在这里插入图片描述
baidu.js 文件内容复制

export default {
  init: function () {
    const AK = "XA593VRNWexLOde7AAHzVAuStbPwpmf7"; //你的AK
    const BMap_URL =
      "https://api.map.baidu.com/api?v=2.0&ak=" +
      AK +
      "&s=1&callback=onBMapCallback";
    return new Promise((resolve, reject) => {
      // 如果已加载直接返回
      if (typeof BMap !== "undefined") {
        resolve(BMap);
        return true;
      }
      // 百度地图异步加载回调处理
      window.onBMapCallback = function () {
        resolve(BMap);
      };
      let getCurrentCityName = function () {
        return new Promise(function (resolve, reject) {
          let myCity = new BMap.LocalCity();
          myCity.get(function (result) {
            resolve(result.name);
          });
        });
      };
      // 插入script脚本
      let scriptNode = document.createElement("script");
      scriptNode.setAttribute(type, "text/javascript");
      scriptNode.setAttribute("src", BMap_URL);
      document.body.appendChild(scriptNode);
    });
  },
};

4.2 vue.config.js文件 代理配置
在这里插入图片描述
代理的内容 复制

  publicPath: "/",
  devServer: {
    proxy: {
      // // 本地代理环境配置
      "/baidu": {
        target: "https://api.map.baidu.com",
        ws: true,
        changOrigin: true, //允许跨域
        pathRewrite: {
          "^/baidu": "", //请求的时候使用这个/baidu 就可以
        },
      },
    }, //指向开发环境 API 服务器
  },

4.3 在请求拦截器中 拦截 含有 ‘ak’ 的字段
在这里插入图片描述
拦截器的内容 复制

 // 百度地图 如果url纯在ak字段,修改baseUrl
      if (config.url.indexOf("ak") > -1) {
        config.baseURL = "";
      }

解决跨域的第二种方案(使用 jsonp)

1- 安装依赖包 npm install vue-jsonp --save
2- main.js 中引入
在这里插入图片描述
3-vue页面中使用:
在这里插入图片描述
在这里插入图片描述

template

<template>
  <div>
    <a-button type="primary" @click="openMap"
      ><a-icon type="environment" />定位</a-button
    >

    <a-modal
      title="新增定位"
      :visible="visible"
      okText="保存"
      @cancel="cancel"
      @ok="submitItem"
    >
      <!-- <div class="searcharea">
        <a-input-search placeholder="输入地点" @search="onSearchArea" />
      </div> -->
      <!-- ak="33B192o1jPaqOHASGGAIkoMuwi8W76j3"  -->
      <baidu-map
        class="map"
        :center="center"
        :zoom="zoom"
        @ready="handler"
        :scroll-wheel-zoom="true"
        @click="clickEvent"
        ak="XA593VRNWexLOde7AAHzVAuStbPwpmf7"
      >
        <!-- 地图控件位置 -->
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
        <!-- 百度搜索 -->
        <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
        <!-- 定位位置 -->
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
          @locationSuccess="getLoctionSuccess"
        ></bm-geolocation>
        <!-- 地图容器 -->
        <bm-view
          :style="{
            width: '100%',
            height: this.clientHeight + 'px',
            flex: 1,
            marginBottom: '-30px',
          }"
        >
        </bm-view>
        <bm-marker
          :position="{ lng: center.lng, lat: center.lat }"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        >
        </bm-marker>
        <!-- 百度搜索框 ===================start-->
        <bm-control :offset="{ width: '10px', height: '10px' }">
          <bm-auto-complete
            v-model="areaaddress"
            :sugStyle="{ zIndex: -999999 }"
            style="display: none"
          >
            <input
              type="text"
              placeholder="请输入搜索关键字"
              class="serachinput"
              v-model="areaaddress"
              @blur="changeclick"
            />
          </bm-auto-complete>
        </bm-control>
        <bm-local-search
          :keyword="areaaddress"
          :auto-viewport="true"
          style="width: 0px; height: 0px; overflow: hidden; display: none"
        ></bm-local-search>

        <!-- 百度搜索框 =============================end -->
      </baidu-map>
      <div class="demo-input-suffix">
        <p>经度:</p>
        <p>{{ locData.longitude }}</p>
        <p>纬度:</p>
        <p>{{ locData.latitude }}</p>
        <p>位置:</p>
        <p>{{ areaaddress }}</p>
      </div>
    </a-modal>
  </div>
</template>

script

<script>
import myBMap from "../../api/baidu.js";
import {
  BaiduMap,
  BmNavigation,
  BmView,
  BmGeolocation,
  BmCityList,
  BmControl,
  BmLocalSearch,
  BmAutoComplete,
  BmMarker,
} from "vue-baidu-map";
export default {
  name: "",
  components: {
    BaiduMap,
    BmNavigation,
    BmView,
    BmGeolocation,
    BmCityList,
    BmControl,
    BmLocalSearch,
    BmAutoComplete,
    BmMarker,
  },
  data() {
    return {
      show: true,
      center: { lng: 116.404, lat: 39.915 },
      creating: true,
      zoom: 12,
      mapVisible: false,
      code: "", // 地区编码
      areaaddress: "", //地区省市县镇
      locData: {
        longitude: "",
        latitude: "",
        address: "",
      },
      visible: false,
      clientHeight: "400", // 屏幕高度
      iconUrl: require("../../assets/image/dingwe.png"),
      ak: "XA593VRNWexLOde7AAHzVAuStbPwpmf7",
    };
  },
  mounted() {},
  methods: {
    openMap() {
      this.visible = !this.visible;
    },
    //点击地图监听
    clickEvent(e) {
      // console.log(e, "点击");

      map.clearOverlays();
      let Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), {
        anchor: new BMap.Size(18, 32),
        imageSize: new BMap.Size(36, 36),
      });
      var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat), {
        icon: Icon_0,
      });
      map.addOverlay(myMarker);
      //用所定位的经纬度查找所在地省市街道等信息
      var point = new BMap.Point(e.point.lng, e.point.lat);
      // 获取逆解析方法实例
      var gc = new BMap.Geocoder();
      let _this = this;
      gc.getLocation(point, function (rs) {
        var addComp = rs.addressComponents;
        // console.log(rs, "点击详细地址信息"); //地址信息
        _this.locData.address = rs.address;
      });
      this.locData.longitude = e.point.lng; // 经度
      this.locData.latitude = e.point.lat; // 纬度
      // 通过经纬度获得 地区编码code   使用代理  /baidu 开头
      myBMap.init().then((BMap) => {
        this.$http
          .get(
            "/baidu/reverse_geocoding/v3/?ak=XA593VRNWexLOde7AAHzVAuStbPwpmf7&output=json&coordtype=wgs84ll&extensions_town=true&location=" +
              this.locData.latitude +
              "," +
              this.locData.longitude
          )
          .then((res) => {
            // console.log(res, "编码code");
            this.code = res.result.addressComponent.town_code;
            this.areaaddress =
              res.result.addressComponent.province +
              res.result.addressComponent.city +
              res.result.addressComponent.district +
              res.result.addressComponent.town;
            this.locData.longitude = res.result.location.lng; // 经度
            this.locData.latitude = res.result.location.lat; // 纬度
          });
      });
    },
    /**定位成功回调
     */
    getLoctionSuccess(point, AddressComponent, marker) {
      map.clearOverlays();
      let Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), {
        anchor: new BMap.Size(18, 32),
        imageSize: new BMap.Size(36, 36),
      });
      var myMarker = new BMap.Marker(
        new BMap.Point(point.point.lng, point.point.lat),
        { icon: Icon_0 }
      );
      map.addOverlay(myMarker);
      this.locData.longitude = point.point.lng;
      this.locData.latitude = point.point.lat;
    },

    // 搜索详细定位地址获得经纬度再获得编码code =============================start
    changeclick() {
      console.log("经纬度");
      let that = this;

      // 通过区域名获得 经纬度 精确度不准 偏差较大 使用代理  /baidu 开头
      myBMap.init().then((BMap) => {
        this.$http
          .get(
            "/baidu/geocoding/v3/?&output=json&ak=XA593VRNWexLOde7AAHzVAuStbPwpmf7&address=" +
              that.areaaddress
          )
          .then((res) => {
            console.log(res, "地区经纬度");
            var lng = res.result.location.lng;
            var lat = res.result.location.lat;
            lng = parseFloat(lng) - 0.008774687519; // 解决误差大问题
            lat = parseFloat(lat) - 0.00374531687912;
            that.locData.longitude = lng; // 经度
            that.locData.latitude = lat; // 纬度
            that.$http
              .get(
                "/baidu/reverse_geocoding/v3/?ak=XA593VRNWexLOde7AAHzVAuStbPwpmf7&output=json&coordtype=wgs84ll&extensions_town=true&location=" +
                  lat +
                  "," +
                  lng
              )
              .then((res) => {
                that.code = res.result.addressComponent.town_code;
              });
          });
      });
    },
    // ===================================================end
    // 获得当前位置
    handler({ BMap, map }) {
      const hide = this.$message.loading("正在获取城市信息");
      let _this = this; // 设置一个临时变量指向vue实例,因为在百度地图回调里使用this,指向的不是vue实例;

      // 获取自动定位方法
      var geolocation = new BMap.Geolocation();
      // 获取自动定位获取的坐标信息
      geolocation.getCurrentPosition(
        function (r) {
          _this.center = { lng: r.longitude, lat: r.latitude }; // 设置center属性值
          _this.autoLocationPoint = { lng: r.longitude, lat: r.latitude }; // 自定义覆盖物
          _this.initLocation = true;
          setTimeout(hide, 1000);
        },
        { enableHighAccuracy: true }
      );
      window.map = map;
    },

    submitItem() {
      if (this.areaaddress != "") {
        this.$emit("reload", this.areaaddress, this.code, this.locData);
        this.visible = false;
        this.areaaddress = "";
        this.code = "";
        this.locData.longitude = "";
        this.locData.latitude = "";
      } else {
        this.$message.error("请点击地图选择位置");
      }
    },

    cancel() {
      this.creating = true;
      this.visible = false;
      this.areaaddress = "";
      this.code = "";
      this.locData.longitude = "";
      this.locData.latitude = "";
    },
  },
};
</script>

style

<style scoped lang="less">
/deep/ .ant-modal {
  width: 90% !important;
  margin: 0 auto;
}
.bm-view {
  width: 100%;
  height: 400px;
}
.demo-input-suffix {
  margin-top: 40px;
  z-index: 999;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  p {
    margin-left: 15px;
  }
}
.searcharea {
  margin: 0px auto 20px;
  width: 40%;
}
.serachinput {
  width: 800px;
  height: 38px;
  box-sizing: border-box;
  padding: 9px;
  border: 1px solid #dddee1;
  line-height: 20px;
  font-size: 16px;
  color: #333;
  position: relative;
  border-radius: 4px;
  -webkit-box-shadow: #666 0px 0px 10px;
  -moz-box-shadow: #666 0px 0px 10px;
  box-shadow: #666 0px 0px 10px;
  display: none;
}
/deep/ .citylist_popup_main .city_content_top {
  height: 40px;
}
/deep/ #selCityWd {
  height: 24px;
}
</style>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐