1、到高德地图开放平台申请key
2、npm安装vue-amap
3、在main.js中引入并初始化

import AMap from 'vue-amap';
Vue.use(AMap);

import $ from 'jquery'
  // 初始化vue-amap
AMap.initAMapApiLoader({
  // 高德key
  key: 'd5486742b76ab0969e4c3ce26f46dfc6',
  // 插件集合 (插件按需引入)
  plugin: ['AMap.Geolocation','Geolocation','AMap.DistrictSearch'],
  v: '1.4.4'
});

4、页面引用amap(注意这个ref的属性是和后面地图的视图自适应的时候对应的)el-amap-polygon的属性可参考[el-amap-polygon属性]

  <div class="mapContainer">
      <div class="amap-page-container" v-bind:style="{height: heightData}">
        <el-amap vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo" ref="map">
          <el-amap-polygon
            strokeColor="#4ea8f8"
            strokeOpacity="0.8"
            fillColor="#c9ebf7"
            fillOpacity="0.5"
            v-for="(polygon, index) in polygons"
            :key="index"
            strokeWeight="1"
            :path="polygon.Ce.path"
          ></el-amap-polygon>
        </el-amap>
      </div>
    </div>

5、页面参数

  data() {
    return {
      heightData: "600px",
      zoom: 7,
      center: [116.244694, 39.517344],
      window: "",
      polygons: [],
      district: null,
    };
  },

6、具体方法

drawBounds() {
      var that = this;
      //加载行政区划插件
      if (!that.district) {
        //实例化DistrictSearch
        var opts = {
          subdistrict: 0, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "city", //查询行政级别为 市
        };
        that.district = new AMap.DistrictSearch(opts);
      }
      //行政区查询
      let code = that.listDate.city + "";
      that.district.search(code, function (status, result) {
        that.polygons = [];
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.4,
              fillColor: "#80d8ff",
              strokeColor: "#0091ea",
            });
            that.polygons.push(polygon);
          }
        }
        console.log("polygons");
        console.log(that.polygons);
        AMap.Polygon.bind(that.polygons);
        that.$refs.map.$amap.setFitView(that.polygons); //视口自适应
      });
    },
  mounted: function () {
    setTimeout(() => {
      this.drawBounds();
    }, 200);
  },

注意:created调用drawBounds时如果不加setTimeout的话会出现类似如下的间歇性报错。原因是因为AMap初始化是个异步过程,在AMap还没初始化完成时就调用了它,所以就不存在了。解决办法也很简单,给使用AMap的方法加个setTimeout延后一点时间调用就可以了

选择里插入图片描述
选择北京市海淀区地图锁展示的效果

Logo

前往低代码交流专区

更多推荐