基于class封装的高德地图定位选址及搜索功能(vue、react均可用)

发布时间 2023-11-07 16:22:54作者: 你风致
import AMapLoader from '@amap/amap-jsapi-loader';
export default class AMaps {
  options: any; //初始参数
  instance: any; //实例
  geocoder: any; //地理编码
  placeSearch: any; //地址搜索
  map: any;
  marker: any; //标记
  address: any; //地址信息
  constructor(options) {
    this.options = options;
  }
  initMap() {
    return new Promise((resolve, reject) => {
      AMapLoader.load({
        key: this.options.key || '******', // 申请好的Web端开发者Key,首次调用 load 时必填
        version: this.options.version || '1.4.15', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.PlaceSearch', 'AMap.Geocoder'].concat(this.options.plugins), // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.instance = AMap;
          this.geocoder = new AMap.Geocoder({ extensions: 'all' });
          this.placeSearch = new AMap.PlaceSearch({ extensions: 'all', pageSize: 15 });
          this.map = new AMap.Map(
            this.options.dom,
            this.options.setting || {
              //设置地图容器id
              viewMode: '3D', //是否为3D地图模式
              zoom: 12, //初始化地图级别
              animateEnable: false,
            }
          );
          const ToolBar = new AMap.ToolBar();
          const Scale = new AMap.Scale();

          this.map.addControl(ToolBar);
          this.map.addControl(Scale);

          const marker = new this.instance.Marker({
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            position: [22, 22],
            offset: new this.instance.Pixel(-10, -35),
            visible: false,
          });
          this.marker = marker;
          this.map.add(marker);

          this.map.on('click', (e) => {
            this.setPosition(e.lnglat);
          });
          resolve(true);
        })
        .catch((e) => {
          console.log(e);
          reject(e);
        });
    });
  }
  //地图点击定位标记及展示
  setPosition(position) {
    this.geocoder.getAddress(position, async (status, result) => {
      //console.log(status, result);
      if (status === 'complete' && result.info === 'OK') {
        const { addressComponent, formattedAddress } = result.regeocode;
        const { province, city, district } = addressComponent;
        this.address = { province, city, district, detail: formattedAddress };
        this.marker.setPosition(position);
        this.marker.show();

        const infoWindow = new this.instance.InfoWindow({
          anchor: 'bottom-center',
          content: `<div style="padding: 10px;">${result.regeocode.formattedAddress}</div>`,
          offset: new this.instance.Pixel(0, -38),
        });
        infoWindow.open(this.map, position);
        //this.address = await this.translateAddress(this.address);
        //console.log(this.address);
      }
    });
  }
  //重新设置地图中心点
  changeMapCenter(position) {
    this.map.setZoomAndCenter(16, position);
  }
  //地址搜索功能,返回所有结果集
  search(str: string) {
    return new Promise((resolve, reject) => {
      this.placeSearch.search(str, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          resolve(result);
        }
      });
    });
  }
  //选择地址移动到地址处并展示,为了配合搜索选择后重新定位
  // position:坐标; option:完整位置对象信息
  selectFun(position, option) {
    this.changeMapCenter(position);

    const { pname, cityname, adname, address, name } = option;
    this.address = { province: pname, city: cityname, district: adname, detail: address + name };
    this.marker.setPosition(position);
    this.marker.show();

    const infoWindow = new this.instance.InfoWindow({
      anchor: 'bottom-center',
      content: `<div style="padding: 10px;">${
        pname + (cityname === pname ? '' : cityname) + adname + address + name
      }</div>`,
      offset: new this.instance.Pixel(0, -38),
    });
    infoWindow.open(this.map, position);
    //this.address = await this.translateAddress(this.address);
  }
  //获取地址信息
  getAddress() {
    return this.address;
  }
  //设置地址信息,取搜索结果集的第一个值进行设置
  setAddress(str: string) {
    this.search(str).then((res: any) => {
      if (res.info === 'OK') {
        let firstObj = res.poiList.pois[0];
        let position = [firstObj.location.lng, firstObj.location.lat];
        this.selectFun(position, firstObj);
      }
    });
  }
}

使用方式:

<div id="amapmain" style={{ height: '100%' }}></div>

this.newMap = new aMaps({
  dom: 'amapmain',
});

this.newMap.initMap()