高德地图搜索+点击获取位置信息

高德地图.png

1.远程搜索功能

:remote-method远程搜索,remoteMethod函数
    <!-- el-select地点位置搜索框 -->
    <el-select
      v-model="searchValue"
      class="search-ipt"
      size="mini"
      filterable
      remote
      reserve-keyword
      placeholder="请输入关键词"
      :remote-method="remoteMethod"
      :loading="loading"
    >
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>

1.1 地图初始化

initMap()mounted中触发

   // 地图初始化
    initMap() {
      let that = this;
      // loadMap()函数需要从单独的异步加载js文件引入
      loadMap().then((AMap) => {
        that.theMap = new AMap.Map(this.$refs.amap, {
          center: new AMap.LngLat(116.297, 39.948), //设置中心点
          zoom: 10, // 地图放大倍数
          resizeEnable: true,
        });
        that.geoCoder = new AMap.Geocoder();
        that.handlerMapClick();
      });
    },

loadMap.js

/**
 * 动态加载高德地图
 *
 * @export
 * @param {*} key 高德地图key
 * @param {*} plugins 高德地图插件
 * @param {string} [v='1.4.14'] 高德地图版本
 * @returns
 */
export default function loadMap() {
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.appendChild(
    document.createTextNode(`window._AMapSecurityConfig = {
      securityJsCode:'这里需要放高德地图密钥',
    }`)
  )
  document.body.appendChild(script)
  return new Promise(function (resolve, reject) {
    // 如果有map引入,需要删除,因为这里需要引入另外的key来做地图主题定制,需要删除
    if (typeof window.AMap !== 'undefined') {
      const arr = document.getElementsByTagName('script')
      for (let i = 0; i < arr.length; i++) {
        if (
          arr[i].src.indexOf('https://webapi.amap.com/maps') !== -1
        ) {
          arr[i].remove()
        }
      }
      // eslint-disable-next-line no-undef
      // resolve(window.AMap)
      // return true
    }
    window.onCallback = function () {
      // eslint-disable-next-line no-undef
      resolve(window.AMap)
    }
    const key = 'ee523081c32f694f28e901ea5078b5cb'
    const plugins = [
      'AMap.OverView',
      'AMap.MouseTool',
      'AMap.PolyEditor',
      'AMap.RectangleEditor',
      'AMap.PlaceSearch',
      'AMap.DistrictLayer',
      'AMap.CustomLayer',
      'AMap.DistrictSearch',
      'AMap.Geocoder',
      'AMap.AutoComplete'
    ]
    const v = '2.0'
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://webapi.amap.com/maps?v=${v}&key=${key}&plugin=${plugins.join(',')}&callback=onCallback`
    script.onerror = reject
    document.head.appendChild(script)
  })
}

1.2 remoteMethod高德地图远程检索数据

  // data() {
  //   return {
  //     theMap: null,
  //     options: [],
  //     searchValue: "",
  //     chooseList: [],
  //     loading: false,
  //     markers: [],
  //     marker: [],
  //     markersPosition: [],
  //     geoCoder: null,
  //     clickInfo: [],
  //   };
  // },

// 下拉选项获取----搜索成功返回对应的地点数据
    remoteMethod(query) {
      const _this = this;
      console.log("query", query);
      if (query !== "") {
        _this.loading = true;
        // 高德地图获取检索数据
        window.AMap.plugin("AMap.AutoComplete", function () {
          const autoComplete = new window.AMap.Autocomplete({
            city: "全国",
          });
          // console.log(query, 'this.searchValue')
          autoComplete.search(query, function (status, result) {
            // 搜索成功时,result即是对应的匹配数据
            if (status === "complete" && result.tips) {
              console.log(result);
              _this.options = result.tips;
            } else {
              _this.options = [];
            }
            _this.loading = false;
          });
        });
      } else {
        _this.loading = false;
        this.options = [];
      }
    },

1.3 点击下拉列表某个数据,添加到列表数组chooseList

  watch: {
    searchValue(val) {
      if (val) {
        this.chooseList = [
          ...this.chooseList,
          ...this.options.filter((i) => i.id === val),
        ];
        this.options = [];
        this.drawMakers();
        this.searchValue = "";
        console.log("打印chooseList数组", this.chooseList);
      }
    },
  },

1.4 渲染定位点drawMakers函数

    // 定位logo渲染点
    drawMakers() {
      const _this = this;
      _this.theMap.clearMap(); // 清除地图覆盖物
      const markers = this.chooseList.map((item, idx) => {
        console.log(item, idx, "item.....");
        if (item.location) {
          console.log(item.location, "item.location");
          return {
            icon: `//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-${
              idx + 1
            }.png`,
            position: [item.location.lng, item.location.lat],
          };
        }
      });
      // 添加一些分布不均的点到地图上,地图上添加三个点标记,作为参照
      for (let index = 0; index < markers.length; index++) {
        if (markers[index]) {
          new window.AMap.Marker({
            map: _this.theMap,
            icon: markers[index].icon,
            position: [markers[index].position[0], markers[index].position[1]],
            offset: new window.AMap.Pixel(-13, -30),
          });

          _this.theMap.setFitView();
        }
      }
    },

1.5 点击地图添加位置信息

    // 点击地图--放在地图初始化initMap()函数中
    handlerMapClick() {
      this.theMap.on("click", (e) => {
        // 点击坐标
        this.markersPosition = [e.lnglat.lng, e.lnglat.lat]
        // 设置新的标记
        this.setMapMarker();
        // this.drawMakers();
        // 根据坐标获取位置信息
        this.geoCoder.getAddress(this.markersPosition, (status, result) => {
          console.log("点击位置信息status:", status);
          if (status === "complete" && result.regeocode) {
            console.log(result, "定位定位");
            const name = result.regeocode.formattedAddress;
            const addresss = `${result.regeocode.addressComponent.street}${result.regeocode.addressComponent.streetNumber}`;
            const mapObj = {};
            const location = {};
            location.lng = e.lnglat.lng;
            location.lat = e.lnglat.lat;
            mapObj.name = name;
            mapObj.address = addresss;
            mapObj.location = location;
            this.chooseList.push(mapObj);
            console.log(this.chooseList);
            let adcode = result.regeocode.addressComponent.adcode;
          }
        });
      });
    },
    // 设置点击位置的标记
    setMapMarker() {
      let marker = new AMap.Marker({
        map: this.theMap,
        position: this.markersPosition,
      });
      // 将 markers 添加到地图
      this.markers.push(marker);
    },
发表评论 / Comment

用心评论~