关于vue的element-ui web端引入高德地图并获取经纬度

 更新时间:2023年04月25日 09:48:18   作者:wendycwb  
这篇文章主要介绍了关于vue的element-ui web端引入高德地图并获取经纬度,高德地图首先要去申请key和密钥,文中提供了部分实现代码和解决思路,感兴趣的朋友可以学习一下

发版前接到一个临时新需求 ,需要在web端地址选择时用地图,并获取经纬度。 临阵发版之际加需求,真的是很头疼,于是赶紧找度娘,找api。 我引入的是高德地图,首先要去申请key , 和密钥,

首先用npm 安装loader

npm i @amap/amap-jsapi-loader --save

然后在main.js里引入

在这里插入图片描述

这里要注意,还需要在index.html文件里引入这一段,开始我没有引入这段,后面请求高德接口时就会报错

在这里插入图片描述

这里我写了一个组件,后面直接引用就可以 组件内容如下:

在这里插入图片描述

内容有点多,截不完图,下面附上源码:

<template lang="html">
  <el-dialog v-dialogDrag title="选择地点" append-to-body width="600px" :visible.sync="mvisible" :close-on-click-modal="false"
             @close="cancel"
  >
    <div id="amap-container">
      <el-input
        id="search-input"
        v-model="searchValue"
        class="input-with"
        placeholder="请输入地址"
        clearable
        @clear="handelclearInput"
        @keyup.native.enter="onhandelSearch"
      >
        <el-button
          slot="append"
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="onhandelSearch"
        >搜索
        </el-button>
      </el-input>
      <el-row class="margin-top-10 address">
        当前地址是: {{ formattedAddress }}
      </el-row>
      <div id="custom-amap" />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handelSave">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
// const AMap = window.AMap
export default {
  name: 'AMap',
  props: {
    defaultValue: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      mvisible: false,
      defaultCity: '',
      // 地图对象
      map: null,
      // 定位默认地址 | 搜索后选择的地址
      formattedAddress: null,
      // 地址对应的经纬度信息
      position: {},
      // 检索关键字
      searchValue: '',
      // 检索函数对象
      placeSearch: null,
      // 检索结果数据数据
      searchInfoList: [],
      // 地图标记
      marker: '',
      // 地址解析(正向)
      geocoder: '',
      // 地址名称
      name: '',
      adcode: ''
    }
  },
  watch: {
    defaultValue() {
      this.searchValue = this.defaultValue
    },
    visible() {
      this.mvisible = this.visible
      this.searchValue = this.defaultValue
      // this.searchValue = '四川省成都市武侯区'
      this.formattedAddress = this.defaultValue
      // 初始化地图页面
      this.initMap()
    }
  },
  beforeDestroy() {
    // 销毁地图
    this.map.destroy()
  },
  methods: {
    //   初始化地图页面
    initMap() {
      AMapLoader.load({
        key: 'dc4da34d26ef0a0851ce91ce099f6f46', // 申请好的Web端开发者Key,首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: [''] // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map('custom-amap', { // 设置地图容器id
          viewMode: '3D', // 是否为3D地图模式
          zoom: 5, // 初始化地图级别
          resizeEnable: true,
          center: [105.602725, 37.076636] // 初始化地图中心点位置
        })
        // 添加maker
        this.setMaker()
        // 添加鼠标点选地图选择地址
        this.addAmapGeocoder()
        this.onhandelSearch()
      }).catch(e => {
        console.log(e)
      })
    },
    // 添加maker
    setMaker() {
      // eslint-disable-next-line no-undef
      this.marker = new AMap.Marker()
      this.map.add(this.marker)
      // 添加解析地理位置插件
      this.map.plugin('AMap.Geocoder', () => {
        // 异步加载插件
        this.geocoder = new AMap.Geocoder({
          city: this.defaultCity, // 默认:“全国”
          radius: 1000 // 范围,默认:500
        })
      })
    },
    // 添加鼠标点选地图选择地址
    addAmapGeocoder() {
      // 添加maker
      this.setMaker()
      // 地图添加点击事件
      this.map.on('click', function(e) {
        console.log('e.lnglat.getLng()', e.lnglat.getLng())
        // document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
      })
      this.map.on('click', e => {
        console.log('e====', e)
        const lnglat = [e.lnglat.getLng(), e.lnglat.getLat()]
        this.marker.setPosition(lnglat)
        this.geocoder.getAddress(lnglat, (status, result) => {
          if (status === 'complete' && result.regeocode) {
            const res = result.regeocode
            const { adcode, province, city, district } = res.addressComponent
            this.searchValue = res.formattedAddress
            const name = province + city + district
            const sdata = { adcode, lng: lnglat[0], lat: lnglat[1], name }
            this.searchSuccessData(sdata)
            console.log('result', result)
          } else {
            console.log(JSON.stringify(result))
          }
        })
      })
    },
    // 按钮触发检索
    onhandelSearch() {
      const that = this
      this.geocoder.getLocation(this.searchValue, function(status, result) {
        if (status === 'complete' && result.geocodes.length) {
          const { lng, lat } = result.geocodes[0].location
          const { province, city, district } = result.geocodes[0].addressComponent
          const { adcode } = result.geocodes[0]
          const name = province + city + district
          const sdata = { adcode, lng, lat, name }
          that.searchSuccessData(sdata)
          that.marker.setPosition([lng, lat])
          that.map.add(that.marker)
          that.map.setFitView(that.marker)
        } else {
          this.$message.error('根据地址查询位置失败')
        }
      })
    },
    searchSuccessData(res) {
      this.formattedAddress = this.searchValue
      this.adcode = res.adcode
      this.name = res.name
      this.position = { lng: res.lng, lat: res.lat }
    },
    // 清除input里的值,清除搜索结果,再次初始化map
    handelclearInput() {
      document.querySelector('#searchResultPanel').innerHTML = ''
    },
    // 保存当前选择的地址,分发事件
    handelSave() {
      this.searchValue = this.formattedAddress
      const { lat, lng } = this.position
      if (lat && lng) {
        const data = {
          name: this.name,
          adcode: this.adcode,
          // 地址名称
          address: this.formattedAddress,
          // 纬度lat
          lat,
          // 经度lng
          lng
        }
        this.$emit('getPosition', true, data)
      } else {
        this.$message.error('请选择地址获取经纬度')
      }
    },
    cancel() {
      this.$emit('getPosition', false)
    }
  }
}
</script>

<style scoped lang="scss">
#amap-container {
  margin: 20px;

  .el-input__clear {
    line-height: 34px;
    /*top: 20px;*/
  }

  #custom-amap {
    height: 30vh;
    width: 100%;
    margin-top: 10px;
    border: 1px solid #ccc;
  }

  .input-with {
    /*position: fixed;*/
    /*top: 40px;*/
    z-index: 1;
    width: 580px;
  }

  .address {
    color: #373737;
  }

}

.amap-sug-result {
  z-index: 99999;
}
</style>

然后在需要的文件里引入就可以: 当我点击这个输入框时,就会弹出地图组件

在这里插入图片描述

这个是地图组件:

在这里插入图片描述

引用组件的代码如下:

 <el-input v-model="basicFormValidate.businessAddressDetail" @click.native="initMapConfirm" />
 <amap :visible="amapVisible" :default-value="basicFormValidate.businessAddressDetail" :business-province-id="basicFormValidate.businessProvinceId" @getPosition="mapConfirm" />
 import Amap from '@/views/common/Amap'
 components: { Amap }

    initMapConfirm() {
      this.amapVisible = true
    },
    mapConfirm(flag, data) {
      this.amapVisible = false
      if (flag) {
        this.basicFormValidate.businessAddressDetail = data.address
        this.basicFormValidate.businessAddressLatitude = data.lat
        this.basicFormValidate.businessAddressLongitude = data.lng
        this.basicFormValidate.businessProvinceId = data.businessProvinceId
      }
    }

最后的结果就是这样的

在这里插入图片描述

如果说之前有地址,那会代入并反向定位,获取其经纬度

在这里插入图片描述

到此这篇关于关于vue的element-ui web端引入高德地图并获取经纬度的文章就介绍到这了,更多相关element-ui高德地图获取经纬度内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vue 3.0自定义指令的使用入门

    Vue 3.0自定义指令的使用入门

    在 Vue 的项目中,我们经常会遇到 v-if、v-show、v-for 或 v-model 这些内置指令,它们为我们提供了不同的功能。除了使用这些内置指令之外,Vue 也允许注册自定义指令。接下来,将使用Vue 3官方文档自定义指令章节中使用的示例,来一步步揭开自定义指令背后的秘密。
    2021-05-05
  • Vue使用el-dialog关闭后重置表单方式

    Vue使用el-dialog关闭后重置表单方式

    这篇文章主要介绍了Vue使用el-dialog关闭后重置表单方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • vue项目嵌套iframe实现发送、接收数据

    vue项目嵌套iframe实现发送、接收数据

    这篇文章主要介绍了vue项目嵌套iframe实现发送、接收数据,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • Vue中的Ajax 配置代理slot插槽的方法详解

    Vue中的Ajax 配置代理slot插槽的方法详解

    这篇文章主要介绍了Vue中的Ajax 配置代理 slot插槽的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • vue切换页面(路由)时如何保持滚动条回到顶部

    vue切换页面(路由)时如何保持滚动条回到顶部

    这篇文章主要介绍了vue 切换页面(路由)时如何保持滚动条回到顶部问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • 在vue中使用setInterval的方法示例

    在vue中使用setInterval的方法示例

    这篇文章主要介绍了在vue中使用setInterval的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • vxe-list vue 如何实现下拉框的虚拟列表

    vxe-list vue 如何实现下拉框的虚拟列表

    这篇文章主要介绍了vxe-list vue 如何实现下拉框的虚拟列表,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • vue实现分页的三种效果

    vue实现分页的三种效果

    这篇文章主要为大家详细介绍了vue实现分页的三种效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-06-06
  • Vue拖拽组件开发实例详解

    Vue拖拽组件开发实例详解

    本文重点给大家介绍Vue拖拽组件开发实例,拖拽的原理是手指在移动的过程中,实时改变元素的位置即top和left值,使元素随着手指的移动而移动。对实例代码感兴趣的朋友跟随脚本之家小编一起学习吧
    2018-05-05
  • Vue动态组件 component :is的使用代码示范

    Vue动态组件 component :is的使用代码示范

    vue 动态组件用于实现在指定位置上,动态加载不同的组件,这篇文章主要介绍了Vue动态组件 component :is的使用,需要的朋友可以参考下
    2023-09-09

最新评论