前端用Antd或者element加vue2配合高德地图实现拖拽选择位置,搜索选址,放大缩小等

这个博客介绍了一个Vue.js组件,用于在地图上选择和确认地址。组件使用了高德地图API,实现了地图加载、定位、搜索、标记等功能,并提供了详细的配置和事件处理。用户可以输入地址进行搜索,或者点击地图选择位置,最终确认使用的地址。
摘要由CSDN通过智能技术生成

1.准备工作,下包

npm i @amap/amap-jsapi-loader

 2.组件代码

<template>

  <j-modal title="标题" :width="640"  :visible="visible" @cancel="handleCancel"

    :bodyStyle="{ maxheight: 500 + 'px' }" footer>

    <div id="amap-container">

      <a-row class="margin-top-10 address">

        当前地址是: {{ formattedAddress }}

        <el-button size="small" type="primary" @click="handelSave">确认使用该地址</el-button>

      </a-row>

      <a-input id="search-input" v-model="searchValue" class="input-with" placeholder="请输入地址进行搜索,按回车键确认" clearable

        @clear="handelclearInput" @keyup.native.enter="handelSearch">

        <a-button slot="append" size="small" type="primary"  @click="handelSearch">搜索</a-button>

      </a-input>

      <div id="searchResultPanel" />

     

      <div id="custom-amap" />

    </div>

  </j-modal>

</template>

<script>

window._AMapSecurityConfig = {

    securityJsCode:'密钥',

  }

import AMapLoader from '@amap/amap-jsapi-loader'

export default {

  name: 'AMap',

  props: {

    defaultValue: {

      type: String,

      default: ''

    },

    lat: {

      type: String | Number,

      default: ''

    },

    lon: {

      type: String | Number,

      default: ''

    }

  },

  data() {

    return {

      defaultCity: '苏州',

      // 地图对象

      map: null,

      // 定位默认地址 | 搜索后选择的地址

      formattedAddress: '填写默认的地址',

      // 地址对应的经纬度信息

      position: {

        address:'填写默认的地址 ',

        lat:默认地址的纬度(数字),

        lng:默认地址的经度(数字)

      },

      // 检索关键字

      searchValue: '',

      // 检索函数对象

      placeSearch: null,

      // 检索结果数据数据

      searchInfoList: [],

      // 地图标记

      marker: '',

      // 地址解析(正向)

      geocoder: '',

      // 地址名称

      name: '',

      visible: false,

    };

  },

  watch: {

    defaultValue() {

      this.formattedAddress = this.defaultValue;

     

    }

  },

  created(){

      this.formattedAddress = this.defaultValue?this.defaultValue:'填写默认地址'

  },

  mounted() {

    // 初始化地图页面

    this.initMap();

  },

  beforeDestroy() {

    // 销毁地图

    this.map.destroy();

  },

  methods: {

    // 取消

    handleCancel() {

      this.visible = false

    },

    //   初始化地图页面

    initMap() {

      const that = this

      AMapLoader.load({

        key:"自己申请",

        version:"1.4.15",

      }).then(AMap=>{

        console.log(AMap)

        that.map = new AMap.Map('custom-amap', {

          resizeEnable: true,

          zoom: 16,

          center: that.lat&&that.lon?[that.lon,that.lat]:[默认经度(数字), 默认纬度(数字)],

          showMarker:false,

          showButton:false

        });

        // 添加工具栏

        that.map.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView'], () => {

          // 工具条

          const toolbar = new AMap.ToolBar();

          // 比例尺

          const scale = new AMap.Scale();

          // 显示鹰眼

          // const overView = new AMap.OverView();

          that.map.addControl(toolbar);

          that.map.addControl(scale);

          // that.map.addControl(overView);

        });

        // 添加maker

        that.setMaker();

        // 添加鼠标点选地图选择地址

        that.addAmapGeocoder();

        // 添加定位

        that.addAMapGeolocation();

        // 添加检索提示

        that.addAMapAutocompletePlaceSearch();

      }).catch(err=>{

        console.log(err)

      })

     

    },

    // 添加maker

    setMaker() {

      this.marker = new AMap.Marker();

      this.map.add(this.marker);

      // 添加解析地理位置插件

      this.map.plugin('AMap.Geocoder', () => {

        // 异步加载插件

        this.geocoder = new AMap.Geocoder({

          city: this.defaultCity, // 默认:“全国”

          radius: 500 // 范围,默认:500

        });

      });

    },

    // 添加鼠标点选地图选择地址

    addAmapGeocoder() {

      // 添加maker

      this.setMaker();

      // 地图添加点击事件

      this.map.on('click', e => {

        console.log(e)

        const lnglat = [e.lnglat.lng, e.lnglat.lat];

        this.marker.setPosition(lnglat);

        this.geocoder.getAddress(lnglat, (status, result) => {

          if (status === 'complete' && result.regeocode) {

            const res = result.regeocode;

            const data = {

              // 地址名称

              address: res.formattedAddress,

              // 纬度lat

              lat: lnglat[1],

              // 经度lng

              lng: lnglat[0]

            };

            this.formattedAddress = res.formattedAddress;

            this.position = data;

          } else {

            alert(JSON.stringify(result));

          }

        });

      });

    },

    // 添加自动定位

    addAMapGeolocation() {

      this.map.plugin('AMap.Geolocation', () => {

        const geolocation = new AMap.Geolocation({

          // 是否使用高精度定位,默认:true

          enableHighAccuracy: true,

          // 设置定位超时时间,默认:无穷大

          timeout: 10000,

          // 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)

          buttonOffset: new AMap.Pixel(200, 200),

          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false

          zoomToAccuracy: true,

          //  定位按钮的排放位置,  RB表示右下

          buttonPosition: 'RB'

        });

        // 获取当前位置

        geolocation.getCurrentPosition();

        // 添加定位当前城市成功监听

        AMap.event.addListener(

          geolocation,

          'complete',

          this.onCurrentPositionComplete

        );

        // 添加定位当前城市发生错误监听

        AMap.event.addListener(

          geolocation,

          'error',

          this.onCurrentPositionError

        );

      });

    },

    // 添加检索提示检索

    addAMapAutocompletePlaceSearch() {

      // 自动提示

      this.map.plugin('AMap.Autocomplete', () => {

        const auto = new AMap.Autocomplete({

          city: this.defaultCity,

          input: 'search-input'

        });

        // 添加检索监听

        AMap.event.addListener(auto, 'select', this.onSelectAutocomplete);

      });

      // 检索服务

      AMap.service(['AMap.PlaceSearch'], () => {

        // 构造地点查询类

        this.placeSearch = new AMap.PlaceSearch({

          type: '', // 兴趣点类别

          pageSize: 5, // 单页显示结果条数

          pageIndex: 1, // 页码

          city: this.defaultCity, // 兴趣点城市

          citylimit: false, // 是否强制限制在设置的城市内搜索

          map: this.map, // 展现结果的地图实例

          panel: 'searchResultPanel', // 结果列表将在此容器中进行展示。

          autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围

        });

      });

      // 添加检索监听

      AMap.event.addListener(

        this.placeSearch,

        'listElementClick',

        this.onSelectSearch

      );

    },

    // 定位当前城市成功回调

    onCurrentPositionComplete(res) {

      // 添加maker

      this.setMaker();

      const lnglat = [res.position.lng, res.position.lat];

      this.marker.setPosition(lnglat);

      console.log(res, 'res');

      this.formattedAddress = res.formattedAddress;

      this.position = res.position;

    },

    // 定位当前城市发生错误回调

    onCurrentPositionError(err) {

      console.log(err);

    },

    // 按钮触发检索

    handelSearch() {

      this.placeSearch.search(this.searchValue, (status, info) => {

        this.searchInfoList = info.poiList.pois;

      });

    },

    // 选择自动提示数据事件回调

    onSelectAutocomplete(e) {

      this.searchValue = e.poi.name;

      this.handelSearch();

    },

    // 选择检索数据结果事件回调

    onSelectSearch(e) {

      const res = e.data;

      this.formattedAddress = res.cityname + res.adname + res.address;

      this.name = res.name;

      this.position = res.location;

    },

    // 清除input里的值,清除搜索结果,再次初始化map

    handelclearInput() {

      document.querySelector('#searchResultPanel').innerHTML = '';

    },

    // 保存当前选择的地址,分发事件

    handelSave() {

      this.searchValue = this.formattedAddress;

      const { lat, lng } = this.position;

      const data = {

        name: this.name,

        // 地址名称

        address: this.formattedAddress,

        // 纬度lat

        lat,

        // 经度lng

        lng

      };

      console.log(data)

      this.$emit('getPosition', data);

      this.visible = false

    }

  }

};

</script>

<style lang="scss">

#amap-container {

  .el-input__clear {

    line-height: 34px;

    // top: 20px;

  }

  #custom-amap {

    height: 500px;

    width: 580px;

    margin-top: 10px;

    border: 1px solid #ccc;

  }

  .input-with {

    // position: fixed;

    // top: 40px;

    z-index: 1;

    width: 580px;

  }

  .address {

    margin-bottom: 10px;

    color: #373737;

  }

}

.amap-sug-result {

  z-index: 99999;

}

.amap_lib_placeSearch{

  width: 580px;

  height: 170px;

  overflow-y: auto;

}

</style>

3.组件使用

  <amap ref="amapModel" :lat="postForm.latitude" :lon="postForm.longitude" :default-value="postForm.detailedAddress" @getPosition="getPosition" />

 data() {

    return {

      postForm: {

        detailedAddress: '',

        longitude: '',

        latitude: ''

      },}}

 methods: {

 //打开地图选择

 golocate(){

      this.$refs.amapModel.visible = true

      this.$refs.searchValue = null

      this.$nextTick(()=>{

        this.$refs.amapModel.initMap()

      })

    },

// 获取地址信息

    getPosition({ address, lat, lng, name }) {

      this.postForm.detailedAddress = address;

      this.postForm.longitude = lng;

      this.postForm.latitude = lat;

       //写自己的逻辑

    },

 }

可以使用以下步骤来实现文件导入导出功能: 1. 安装 antd 和 xlsx 库 ``` npm install ant-design-vue xlsx --save ``` 2. 在 Vue 组件中引入 antd 和 xlsx ```javascript import { Button, Upload, message } from 'ant-design-vue'; import XLSX from 'xlsx'; ``` 3. 在 Vue 组件中添上传组件和下载按钮 ```html <template> <div> <a-button type="primary" @click="downloadExcel">下载Excel模板</a-button> <a-upload :before-upload="beforeUpload" :show-upload-list="false"> <a-button>上传Excel文件</a-button> </a-upload> </div> </template> ``` 4. 实现下载 Excel 模板功能 ```javascript downloadExcel() { const fileName = 'example.xlsx'; const headers = ['姓名', '年龄', '性别']; const data = [['张三', 18, '男'], ['李四', 20, '女'], ['王五', 22, '男']]; const worksheet = XLSX.utils.aoa_to_sheet([headers, ...data]); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); XLSX.writeFile(workbook, fileName); } ``` 5. 实现上传 Excel 文件功能 ```javascript beforeUpload(file) { const reader = new FileReader(); reader.onload = (e) => { const data = e.target.result; const workbook = XLSX.read(data, { type: 'binary' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const headers = ['姓名', '年龄', '性别']; const fields = ['name', 'age', 'gender']; const records = XLSX.utils.sheet_to_json(worksheet, { header: headers, range: 1 }); const valid = records.every((record) => fields.every((field) => record[field])); if (valid) { // 调用后端接口保存数据 message.success('上传成功'); } else { message.error('上传失败,请检查文件格式'); } }; reader.readAsBinaryString(file); return false; } ``` 在 beforeUpload 方法中,我们使用 FileReader 对象读取上传的文件内容,并使用 XLSX 库解析 Excel 文件。如果文件格式正确,就将数据传递给后端接口进行保存,否则提示用户上传失败。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值