网络编程
位置:首页>> 网络编程>> JavaScript>> 关于vue的element-ui web端引入高德地图并获取经纬度

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

作者:wendycwb  发布时间:2023-07-02 16:48:01 

标签:element-ui,web,高德地图,获取经纬度

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

首先用npm 安装loader

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

然后在main.js里引入

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

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

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

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

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

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

<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>

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

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

这个是地图组件:

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

引用组件的代码如下:

<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端引入高德地图并获取经纬度

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

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

来源:https://blog.csdn.net/sinat_41200024/article/details/130274875

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com