vue2中高德Api的使用

如果项目中有多个页面使用地图,容器 id 不能一样!!!
不要忘记销毁地图组件 map.destroy();

页面效果

效果图

实现代码
              <!-- 远程搜索 -->
              <el-autocomplete
                style="width: 100%"
                popper-class="autoAddressClass"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="false"
                @select="handleSelect"
                type="textarea"
                autosize
                placeholder="请输入位置进行选择"
                size="small"
                clearable
                v-model="form.position"
                :maxlength="100"
              >
                <template slot-scope="{ item }">
                  <div class="addressItem">
                    <i class="el-icon-location-outline" size="16"></i>
                    <span class="flex-1 pl-2"
                      >{{ item.name }}({{ item.address }})</span
                    >
                  </div>
                </template>
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-location-information"
                ></i>
              </el-autocomplete>
          <!-- 地图容器 -->
          <div
            class="bg-gray"
            style="width: 100%; height: 500px"
            v-loading="loading1"
            element-loading-text="地图加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.2)"
          >
            <div id="container1" class="w100 h100" />
          </div>
import AMapLoader from "@amap/amap-jsapi-loader";
import redIcon from "../components/img/point-red1.png";
//秘钥
window._AMapSecurityConfig = {
  securityJsCode: "yourSecurityJsCode",
};
  data() {
    return {
      // 遮罩层
      loading1: true,
      // 表单参数
      form: {},
      map: null,
      geocoder: null,
    };
  },
    // 地图
    initAMap(lng, lat) {
      console.log("initAMap");
      AMapLoader.load({
        key: "yourKey", // 申请好的Web端开发者Key,首次调用 load 时必填
        // version: "v1.4.15", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: [
          // "AMap.ControlBar",
          // "AMap.ToolBar",
          // "AMap.Weather",
          // "AMap.CitySearch",
          "AMap.Marker",

          "AMap.AutoComplete",
          "AMap.PlaceSearch",

          // "AMap.MouseTool",
          // "AMap.PolyEditor",
          // "AMap.Driving",
          // "AMap.Polyline",
          // "AMap.Geolocation",
          // "AMap.GraspRoad",
          "AMap.Geocoder",
          // "AMap.GeometryUtil.ringArea",
          // "AMap.DistrictSearch",
          // "AMap.MoveAnimation",
        ], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("container1", {
            // 设置地图容器id
            rotateEnable: true,
            pitchEnable: true,
            zoom: 17,
            pitch: 50,
            rotation: -15,
            viewMode: "3D", //开启3D视图,默认为关闭
            zooms: [2, 20],
            center: [119.421003, 32.393159],
            mapStyle: "amap://styles/normal", //设置地图的显示样式
          });
          this.geocoder = new AMap.Geocoder({
            // city: "010", //城市设为北京,默认:“全国”
            radius: 1000, //范围,默认:500
          });
          let that = this;
          this.map.on("complete", () => {
            that.loading1 = false;
            console.log("地图加载完成", lng, lat);
            if (lng && lat) {
              that.createMarker(lng, lat);
            }
          });
          //为地图注册click事件获取鼠标点击出的经纬度坐标
          this.map.on("click", function (e) {
            // this.form.longitude = e.lnglat.getLng();
            // this.form.latitude = e.lnglat.getLat();
            that.loading1 = true;
            that.regeoCode(e.lnglat.getLng(), e.lnglat.getLat());
          });
        })
        .catch((e) => {
          console.log(e, "initMapErr");
          this.loading1 = false;
        });
    },
    // 创建两个点标记
    createMarker(longitude, latitude, name, address) {
      // 清除地图上所有图形
      if (this.map) {
        this.map.clearMap();
      }
      console.log("createMarker");
      var marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude),
        icon: new AMap.Icon({
          image: redIcon,
          imageSize: new AMap.Size(28, 28),
        }),
      });
      this.map.add(marker);
      //自动适配到合适视野范围
      //无参数,默认包括所有覆盖物的情况
      this.map.setFitView();
      this.loading1 = false;
    },
    // 8-1、地址搜索
    querySearchAsync(val, callback) {
      //val值 cb回调
      AMap.plugin("AMap.Autocomplete", () => {
        // 实例化Autocomplete
        let autoOptions = {
          city: "扬州",
        };
        let autoComplete = new AMap.Autocomplete(autoOptions); // 初始化autocomplete
        // 开始搜索
        autoComplete.search(val, (status, result) => {
          // 搜索成功时,result即是对应的匹配数据
          if (result.info === "OK") {
            console.log(result.tips, "search_result");
            callback(result.tips);
          }
        });
      });
    },
    // 8-2、选择地址
    handleSelect(item) {
      this.form.position = item.district + item.address;
      this.geoCode(this.form.position);
    },
    // 地址 => 经纬度
    geoCode(address) {
      let that = this;
      this.geocoder.getLocation(address, function (status, result) {
        if (status === "complete" && result.geocodes.length) {
          var lnglat = result.geocodes[0].location;
          console.log(lnglat, "lnglat");
          let { lng, lat } = lnglat;
          that.form.longitude = lng;
          that.form.latitude = lat;
          that.createMarker(lng, lat);
        } else {
          that.$modal.msgError("根据地址查询坐标失败");
        }
      });
    },
    // 经纬度 => 地址
    regeoCode(longitude, latitude) {
      this.createMarker(longitude, latitude);
      var lnglat = longitude + "," + latitude;
      let that = this;
      this.geocoder.getAddress(lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          var address = result.regeocode.formattedAddress;
          that.form.position = address;
          that.form.longitude = longitude;
          that.form.latitude = latitude;
        } else {
          that.$modal.msgError("根据经纬度查询地址失败");
        }
      });
    },
.addressItem {
  display: flex;
  justify-content: start;
  align-content: center;
  align-items: center;
}
  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值