> 文章列表 > vue element-ui web端 引入高德地图,并获取经纬度

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

vue 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-inputid="search-input"v-model="searchValue"class="input-with"placeholder="请输入地址"clearable@clear="handelclearInput"@keyup.native.enter="onhandelSearch"><el-buttonslot="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.visiblethis.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.15plugins: [''] // 需要使用的的插件列表,如比例尺'AMap.Scale'等}).then((AMap) => {this.map = new AMap.Map('custom-amap', { // 设置地图容器idviewMode: '3D', // 是否为3D地图模式zoom: 5, // 初始化地图级别resizeEnable: true,center: [105.602725, 37.076636] // 初始化地图中心点位置})// 添加makerthis.setMaker()// 添加鼠标点选地图选择地址this.addAmapGeocoder()this.onhandelSearch()}).catch(e => {console.log(e)})},// 添加makersetMaker() {// eslint-disable-next-line no-undefthis.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() {// 添加makerthis.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.regeocodeconst { adcode, province, city, district } = res.addressComponentthis.searchValue = res.formattedAddressconst name = province + city + districtconst 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 = thisthis.geocoder.getLocation(this.searchValue, function(status, result) {if (status === 'complete' && result.geocodes.length) {const { lng, lat } = result.geocodes[0].locationconst { province, city, district } = result.geocodes[0].addressComponentconst { adcode } = result.geocodes[0]const name = province + city + districtconst 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.searchValuethis.adcode = res.adcodethis.name = res.namethis.position = { lng: res.lng, lat: res.lat }},// 清除input里的值,清除搜索结果,再次初始化maphandelclearInput() {document.querySelector('#searchResultPanel').innerHTML = ''},// 保存当前选择的地址,分发事件handelSave() {this.searchValue = this.formattedAddressconst { lat, lng } = this.positionif (lat && lng) {const data = {name: this.name,adcode: this.adcode,// 地址名称address: this.formattedAddress,// 纬度latlat,// 经度lnglng}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 = falseif (flag) {this.basicFormValidate.businessAddressDetail = data.addressthis.basicFormValidate.businessAddressLatitude = data.latthis.basicFormValidate.businessAddressLongitude = data.lngthis.basicFormValidate.businessProvinceId = data.businessProvinceId}}

最后的结果就是这样的
vue element-ui web端 引入高德地图,并获取经纬度
如果说之前有地址,那会代入并反向定位,获取其经纬度

vue element-ui web端 引入高德地图,并获取经纬度
好了就分享到这儿,备个份,助人达己。
如果说有更好的方便,欢迎交流分享。