Vue.js 加入高德地图的实现代码

 更新时间:2022年12月12日 15:05:14   作者:清雨未尽时  
这篇文章主要介绍了Vue.js 加入高德地图的实现方法,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、功能需求

1.根据输入内容进行模糊查询,选择地址后在地图上插上标记,并更新经纬度坐标显示

2.在地图点击后,根据回传的左边更新地址信息和坐标显示

二、准备

1.申请高德地图账号,创建应用

 2.在应用管理中 获得key 和安全密钥

三、在webstorm中安装 

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

四、防止在使用中AMap无法识别问

        在eslintrc.js中加入配置:

     globals:{
    "AMap": "true"
  }   

五、正式开发

1.创建页面

<template>
  <div>
    <label>消息管理</label>
    <div style="margin-top: 20px">
      <div style="height:520px;">
        <div id="all" style="height:100%">
          <div class="posInput">
            <el-input style="width:100%"
                      id="tipinput"
                      class="form-control input-style"
                      type="text"
                      placeholder="请输入搜索地址"
                      prefix-icon="el-icon-search"
                      v-model="formatAdress"
            >
            </el-input>
          </div>
          <div id="allmap"></div>
          <div class="posSubmit">
            <el-form  ref="form"  label-width="85px" >
              <div class="btn_box" >
                <el-form-item label="经度:" >
                  <el-input style="width:400px" disabled class="form-control input-style" type="text" v-model="longitude"> </el-input>
                </el-form-item>
                <el-form-item label="纬度:" >
                  <el-input style="width:400px"  disabled class="form-control input-style" type="text" v-model="latitude"> </el-input>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

2.页面样式

<style scoped>
#all{
  position: relative;
}
#allmap{
  width: 100%;  height: calc(100%  - 50px);
  font-family: "微软雅黑";
}
.posInput{
  position: absolute;
  z-index: 1;
  width: 80%;
  margin-top: 20px;  margin-left: 10%;
}
.posSubmit{
  position: absolute; z-index: 1; bottom: 0;
  margin-left: 5%;
  width: 90%;
  display: flex;  justify-content: flex-start; align-items: center;
}
.btn_box{
  width: 100%;
  height: 100%;
  display: flex;  ; align-items: center;
}
::v-deep .el-form-item{
  margin-bottom: 0 !important;
}
</style>

3.存储的数据项

data () {
    return {
      map: null,
      marker: null,
      startSeacrh: [],
      stratInfo: {},
      dprops: {
        zoom: 15
      },
      formatAdress: '',
      longitude: '', // 经度
      latitude: '', // 纬度
    }
  }

4.创建地图方法

    mounted () {
    this.initMap()
  },
  methods: {
    initMap () {
      const that = this
      init('allmap', that.dprops).then(AMap => {
        that.map = AMap
        that.map.on('click', that.clickHandler) // 地图点击事件 可获取经纬度等信息
        initScaleTools(that.map, true, false)
        searchAutocomplete(that.map, 'tipinput', function (event) {
          that.handleStartSelect(event)
        })
      }).catch(err => {
        this.$message.error(err)
      })
    },
    clickHandler (event) {
      console.log(event, '起点经纬度 [lng,lat]')
      if (event.lnglat === '') {
        this.$message({
          type: 'warning',
          message: '该地点无经纬度数据,请输入具体一点的地点!',
          duration: 5 * 1000
        })
        return
      }
      if (this.marker) {
        this.map.remove(this.marker)
        this.marker = null
      }
      this.startSeacrh = []
      this.startSeacrh = [event.lnglat.lng, event.lnglat.lat]
      this.marker = new AMap.Marker({
        position: this.startSeacrh
      })
      this.map.add(this.marker)
      this.map.setCenter(this.startSeacrh)
      this.longitude = event.lnglat.lng
      this.latitude = event.lnglat.lat
      let that = this
      getAddressByLngLat(this.startSeacrh, function (status, result) {
        if (status === 'complete') {
          that.formatAdress = result.regeocode.formattedAddress
          let adrComponent = result.regeocode.addressComponent
          that.stratInfo = {
            district: adrComponent.province,
            address: adrComponent.district,
            name: adrComponent.township + adrComponent.street + adrComponent.streetNumber,
            fullAdr: result.regeocode.formattedAddress
          }
        }
      })
    },
    handleStartSelect (event) {
      console.log(event, '起点经纬度 [lng,lat]')
      if (event.poi.location === '') {
        this.$message({
          type: 'warning',
          message: '该地点无经纬度数据,请输入具体一点的地点!',
          duration: 5 * 1000
        })
        return
      }
      if (this.marker) {
        this.map.remove(this.marker)
        this.marker = null
      }
      this.startSeacrh = []
      this.startSeacrh = [event.poi.location.lng, event.poi.location.lat]
      this.formatAdress = event.poi.district + event.poi.address + event.poi.name
      this.longitude = event.poi.location.lng
      this.latitude = event.poi.location.lat
      this.marker = new AMap.Marker({
        position: this.startSeacrh
      })
      this.map.add(this.marker)
      this.map.setCenter(this.startSeacrh)
      this.stratInfo = {
        district: event.poi.district,
        address: event.poi.address,
        name: event.poi.name,
        fullAdr: this.formatAdress
      }
    }
  } 

5.封装好的js文件方法

  initMap.js

import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  securityJsCode: '安全密钥'
}
const initMap = async (config) => {
  return new Promise((resolve, reject) => {
    AMapLoader.load({
      'key': config.key,
      'version': '1.4.15',
      'plugins': [
        'AMap.PolygonEditor' // 插件
      ],
      'AMapUI': {
        'version': '1.1',
        'plugins': []
      },
      'Loca': {
        'version': '1.3.2'
      }
    }).then((AMap) => {
      resolve(AMap)
    }).catch(err => {
      reject(err)
    })
  })
}
export default initMap

map.js

import initMap from './initMap.js'
export const init = (container, props) => {
  const config = {
    key: 'key'
  }
  return new Promise((resolve, reject) => {
    initMap(config).then(AMap => {
      resolve(new AMap.Map(container, { ...props }))
    }).catch(err => {
      reject(err)
    })
  })
}
/**
 * @param {*} map 地图实例
 * @param {Boolean} noScale 不需要比例尺  true表示不需要
 * @param {Boolean} noToolBar 不需要工具栏 true表示不需要
 */
export const initScaleTools = (map, noScale, noToolBar) => {
  if (!noScale) {
    map.plugin(['AMap.Scale'], function () {
      var scale = new AMap.Scale()
      map.addControl(scale)
    })
  }
  if (!noToolBar) {
    map.plugin(['AMap.ToolBar'], function () {
      var tool = new AMap.ToolBar()
      map.addControl(tool)
    })
  }
}
//模糊查询
export const searchAutocomplete = (map, keyword, commpletHandle) => {
  map.clearMap()
  AMap.plugin(['AMap.PlaceSearch', 'AMap.Autocomplete'], function () {
    let autoOptions1 = { input: keyword, city: '全国' }
    let startAutoComplete = new AMap.Autocomplete(autoOptions1)
    AMap.PlaceSearch({
      map: map
    })
    AMap.event.addListener(startAutoComplete, 'select', commpletHandle)
  })
}
 
/**
 *
 * @param {String} LngLat 经纬度
 * @param {Function} callback 回调函数
 * @param {Object} otherProps 其他参数
 */
export const getAddressByLngLat = (LngLat, callback, otherProps) => {
  AMap.plugin('AMap.Geocoder', function () {
    let geocoder = new AMap.Geocoder({
      ...otherProps
    })
 
    geocoder.getAddress(LngLat, function (status, result) {
      callback(status, result)
    })
  })
}
 
const mapJS = {
  init,
  initScaleTools,
  searchAutocomplete,
  getAddressByLngLat
}
export default mapJS

在文件中导入 map.js方法

import {
  init,
  initScaleTools,
  searchAutocomplete,
  getAddressByLngLat
} from '../../utils/map'

六、步骤总结

1.在mounted()中调用 initMap ()初始化地图

2.初始化成功后、添加事件监听:地图点击、模糊查询。添加放大缩小工具栏

init('allmap', that.dprops).then(AMap => {
        that.map = AMap
        that.map.on('click', that.clickHandler) // 地图点击事件 可获取经纬度等信息
        initScaleTools(that.map, true, false)
        searchAutocomplete(that.map, 'tipinput', function (event) {
          that.handleStartSelect(event)
        })
      })

七:效果

到此这篇关于Vue.js 加入高德地图的实现方法的文章就介绍到这了,更多相关Vue.js 加入高德地图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 如何获取this.$store.dispatch的返回值

    如何获取this.$store.dispatch的返回值

    这篇文章主要介绍了如何获取this.$store.dispatch的返回值问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • vue服务端渲染缓存应用详解

    vue服务端渲染缓存应用详解

    vue缓存分为页面缓存、组建缓存、接口缓存,这里我主要说到了页面缓存和组建缓存。接下来通过本文给大家介绍vue服务端渲染缓存应用 ,需要的朋友可以参考下
    2018-09-09
  • 如何正确解决VuePress本地访问出现资源报错404的问题

    如何正确解决VuePress本地访问出现资源报错404的问题

    这篇文章主要介绍了如何正确解决VuePress本地访问出现资源报错404的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • 基于node+vue实现简单的WebSocket聊天功能

    基于node+vue实现简单的WebSocket聊天功能

    最近学习了一下websocket的即时通信,感觉非常的强大,这里我用node启动了一个服务进行websocket链接,然后再vue的view里面进行了链接,进行通信,废话不多说,直接上代码吧
    2020-02-02
  • Vue下拉框回显并默认选中随机问题

    Vue下拉框回显并默认选中随机问题

    这篇文章主要介绍了Vue下拉框回显并默认选中随机问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • vue轻松实现虚拟滚动的示例代码

    vue轻松实现虚拟滚动的示例代码

    移动端网页的日常开发中,偶尔会包含一些渲染长列表的场景,本文主要介绍了vue 虚拟滚动,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Vue-cli3简单使用(图文步骤)

    Vue-cli3简单使用(图文步骤)

    这篇文章主要介绍了Vue-cli3简单使用(图文步骤),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-04-04
  • Vue.js获取被选择的option的value和text值方法

    Vue.js获取被选择的option的value和text值方法

    今天小编就为大家分享一篇Vue.js获取被选择的option的value和text值方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • 如何使用ant-design-vue的Table组件

    如何使用ant-design-vue的Table组件

    这篇文章主要介绍了如何使用ant-design-vue的Table组件,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • VUE的数据代理与事件详解

    VUE的数据代理与事件详解

    这篇文章主要为大家介绍了VUE的数据代理与事件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11

最新评论