在vue中使用高德地图点击打点,搜索打点,高德地图组件封装

一。安装高德地图

javascript 复制代码
npm install @amap/amap-jsapi-loader --save

二、在index.html文件中引入高德地图JavaScript API:

javascript 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 2 AMap Demo</title>
  <script src="https://webapi.amap.com/maps?v=2.0&key=你的key"></script>
</head>
<body>
  <div id="app"></div>
  <script src="/dist/build.js"></script>
</body>
</html>`在这里插入代码片`

三、创建Vue组件,AMapMarker.vue

javascript 复制代码
<template>
  <div class="map-wrap" :style="{ width: width, height: height }">
    <el-form
      :model="formData"
      :rules="rules"
      :disabled="disabled"
      class="mapFormData"
      ref="mapFormData"
    >
      <el-form-item label="关键词" prop="address" label-width="80px">
        <el-input
          v-model="formData.address"
          id="tipinput"
          placeholder="请输入关键词"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div id="container" class="container map"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  props: {
    //地图宽度
    width: {
      type: String,
      default: '100%',
    },
    //地图高度
    height: {
      type: String,
      default: '500px',
    },
    /**
     * 默认显示的地图对象信息
     * 地址 经度 纬度
     *  { address: '', lat: '',lng: '',}
     */
    defaultMapData: {
      type: Object,
      default: () => new Object(),
    },

    //禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      mapInfo: null,
      marker: null,
      searchValue: '',
      formData: {
        address: '',
        lat: '',
        lng: '',
      },
      rules: {},
    }
  },

  watch: {
    defaultMapData: {//默认地图显示的点位
      handler(newV) {
        if ((newV && JSON.stringify != '{}') || newV.lat) {
          this.formData = {...newV} //
          this.initMap()
        } else {
          this.formData = {
            address: '',
            lat: '',
            lng: '',
          }
        }
      },
      deep: true,
      immediate: true,
    },
    disabled: { //地图是否禁用打点
      handler(newV) {
        if (newV) {
          this.setMapEvent(true)
        } else {
          this.setMapEvent(false)
        }
      },
      immediate: true,
    },
  },
  methods: {
    initMap() {
     
      AMapLoader.load({
        key: '你的key',
        version: '2.0',
        plugins: ['AMap.Geocoder', 'AMap.Geolocation', 'AMap.CitySearch'],
        resizeEnable: true,
      })
        .then((AMap) => {
          this.mapInfo = new AMap.Map('container', {
            resizeEnable: true,
            zoom: 16,//缩放等级
            center:[116.397428, 39.90923],//中心点
          })

          if (this.defaultMapData.lat && this.defaultMapData.lng) {//父组件传过来的点 默认点位打点
            this.marker && this.mapInfo.remove(this.marker)
            this.marker = new AMap.Marker({
              position: new AMap.LngLat(this.defaultMapData.lng, this.defaultMapData.lat),
            })
            this.mapInfo.add(this.marker)
            this.setMapCenter(this.defaultMapData.lng, this.defaultMapData.lat)
          }

          const autoOptions = {
            input: 'tipinput',
          }
          AMap.plugin(['AMap.AutoComplete'], () => { //搜索
            const auto = new AMap.AutoComplete(autoOptions)
            auto.on('select', this.adrSelect) //
          })

          this.setMapEvent(this.disabled)
        })
        .catch((e) => {
          //加载错误提示
        })
    },
    setMapCenter(lng, lat) { 
      this.mapInfo.setZoomAndCenter(16, [lng, lat])
    },
    adrSelect(e) {//搜索
      this.setMapCenter(e.poi.location.lng, e.poi.location.lat)
      this.marker && this.mapInfo.remove(this.marker)
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(e.poi.location.lng, e.poi.location.lat),
      })
      this.setFormData( e.poi.location.lng, e.poi.location.lat,e.poi.name)
      this.emitMapData(e.poi.name, e.poi.location.lng, e.poi.location.lat)
      this.mapInfo.add(this.marker)
    },
    addMarker(e) {//添加点位
      this.marker && this.mapInfo.remove(this.marker)
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat),
      })

      this.setFormData(e.lnglat.lng, e.lnglat.lat, this.formData.address)
      this.emitMapData(this.formData.address, e.lnglat.lng, e.lnglat.lat)

      this.mapInfo.add(this.marker)

      const geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: 'all',
      })

      geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], (status, result) => {//转换地址
        if (status === 'complete' && result.regeocode) {
          this.$set(this.formData, 'address', result.regeocode.formattedAddress)
        } else {
        }
      })
      this.setMapCenter(e.lnglat.lng, e.lnglat.lat)
    },
    setFormData(lng, lat, address) {
      this.$set(this.formData, 'address', address)
      this.$set(this.formData, 'lng', lng)
      this.$set(this.formData, 'lat', lat)
    },
    emitMapData(address = this.formData.address, lng = this.formData.lng, lat = this.formData.lat) {  //将已选择的点传给父组件
      this.$emit('getMapData', {
        address,
        lng,
        lat,
      })
    },
    setMapEvent(flg) {
      this.$nextTick(() => {
        if (flg) {
          this.mapInfo && this.mapInfo.off('click', this.addMarker)
        } else {
          this.mapInfo && this.mapInfo.on('click', this.addMarker)
        }
      })
    },
  },
  destroyed() {},
}
</script>

<style lang="less" scoped>
.map-wrap {
  width: 100%;
  height: 500px;
  position: relative;
  .mapFormData {
    position: absolute;
    width: 100%;
    top: 18px;
    left: 0;
    z-index: 99;
    ::v-deep .el-input__inner {
      width: 70%;
    }
  }
  .map {
    width: 100%;
    height: 100%;
  }
  .row {
    margin-top: 10px;
    display: flex;
  }
  .mr20 {
    margin-right: 20px;
  }
}
</style>

四、在需要使用组件的地方引入并使用AMapMarker组件

javascript 复制代码
<template>
  <div :style='width:500px;height:500px;'>
    <AMapMarker @getMapData='getMapData' :defaultMapData='defaultMapData' />
  </div>
</template>

<script>
import AMapMarker from './AMapMarker.vue';

export default {
  components: {
    AMapMarker 
  },
  data(){
  	return {
  		defaultMapData:{},//默认点位信息为空
	}
  },
  methods:{
  getMapData(mapInfo){
  console.log('获取到的地图地址经纬度信息:',mapInfo)
  }
}
};
</script>
相关推荐
工业互联网专业29 分钟前
毕业设计选题:基于ssm+vue+uniapp的校园水电费管理小程序
vue.js·小程序·uni-app·毕业设计·ssm·源码·课程设计
豆豆42 分钟前
为什么用PageAdmin CMS建设网站?
服务器·开发语言·前端·php·软件构建
计算机学姐1 小时前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
JUNAI_Strive_ving1 小时前
番茄小说逆向爬取
javascript·python
看到请催我学习1 小时前
如何实现两个标签页之间的通信
javascript·css·typescript·node.js·html5
twins35202 小时前
解决Vue应用中遇到路由刷新后出现 404 错误
前端·javascript·vue.js
qiyi.sky2 小时前
JavaWeb——Vue组件库Element(3/6):常见组件:Dialog对话框、Form表单(介绍、使用、实际效果)
前端·javascript·vue.js
煸橙干儿~~2 小时前
分析JS Crash(进程崩溃)
java·前端·javascript
哪 吒2 小时前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
安冬的码畜日常2 小时前
【D3.js in Action 3 精译_027】3.4 让 D3 数据适应屏幕(下)—— D3 分段比例尺的用法
前端·javascript·信息可视化·数据可视化·d3.js·d3比例尺·分段比例尺