Vue2项目使用高德地图实现地图显示、标记以及获取坐标信息

您所在的位置:网站首页 怎么在高德地图上标记地址呢视频教学 Vue2项目使用高德地图实现地图显示、标记以及获取坐标信息

Vue2项目使用高德地图实现地图显示、标记以及获取坐标信息

2024-07-11 14:39| 来源: 网络整理| 查看: 265

1. 展示效果

在地图上标点之后,直接获得坐标以及具体位置信息:

“https://lbs.amap.com/api/webservice/guide/api/georegeo”,这个网址中给出了地理编码以及逆编码的接口,可以直接调用。

2.注册高德key

进入高德控制台首页我的应用中添加两个KEY“https://console.amap.com/dev/index”;

如图所示:新建一个web端(JS API)和web服务key;

3.导入项目

在项目根目录下使用下载amap插件

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

在main.js中导入AMap插件,这里使用的key为前面申请的两个key中的web端的key;

4.在具体组件中实现获取具体位置信息功能

template定义:

//template

data定义:

var map = {} //地图对象 var marker = {} //标记对象 const markers = [] //标记对象数组 export default { name: 'Map', props:{ //父组件传值 经纬度以及具体信息 需要做双向绑定 storeroomLocation:{ type:String }, storeroomLongitude:{ type:Number }, storeroomLatitude:{ type:Number } }, data() { return { lng: '', lat: '', location:'', MapMsg:'' } }, }

具体实现方法:

createdMap() { const that = this map = new AMap.Map('MapContainer', { zoom: 13, //设置地图的缩放级别 zooms: [8, 20], //设置地图的缩放级别区间 mapStyle: 'amap://styles/normal', //设置地图的显示样式 features: ['road', 'point',], //设置地图的底图元素,缺少则显示全部元素,bg区域面、point兴趣点、road道路及道路标注、building建筑物 }) //绑定地图点击事件 map.on('click', function (e) { map.remove(markers) const { lng, lat } = e.lnglat that.lng = lng that.lat = lat that.location = lng+','+lat // 创建一个 Marker 实例: 标记点信息 var marker = new AMap.Marker({ position: [lng, lat], // 经纬度 anchor: 'center', offset: new AMap.Pixel(0, 0), //创建一个自定义图标实例 icon: new AMap.Icon({ size: new AMap.Size(28, 30), // 图标尺寸 image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png', // 自定义图像的url imageSize: new AMap.Size(27, 30) // 根据所设置的大小拉伸或压缩图片 }), }) //只保留一个标记点 markers.push(marker) map.add(marker) // 获取详细位置信息 web服务key const LocationObj = that.BatchLocationMsg({location:that.location,key:'xxxxxxxxxxxxxxxxxx'}) //此处的xxxx填写前面申请的web服务key LocationObj.then((res)=>{ const {data} = res that.MapMsg = data.regeocode.formatted_address that.$emit('update:storeroomLocation',that.MapMsg) // console.log(typeof that.lng) that.$emit('update:storeroomLongitude',that.lng) that.$emit('update:storeroomLatitude',that.lat) }) }) }, //restapi.amap.com/v3/geocode/ BatchLocationMsg(params){ return axios({ url:'/amap/regeo', method:'GET', params:params }) // getAction('/amap/regeo',params) } 5.注意事项

1.这块代码是对标发送请求获取具体信息的接口,因为产生了跨域问题 ,所以需要在vue.config.js中进行代理操作:

BatchLocationMsg(params){ return axios({ url:'/amap/regeo', method:'GET', params:params })

具体代理实现:

devServer: { port: 3000, proxy: { //添加下面的对象 '/amap': { target: 'https://restapi.amap.com/v3/geocode/', changeOrigin: true, ws: true, pathRewrite: { '^/amap': '' } }, } }

总结:主要注意两个点:

1.功能中包含了使用api的逆编码方法,所以需要使用web服务的key,在导入时使用的key为web端的key,需要使用两个;

2.在调用官方接口时,会产生跨域问题,需要在vue.config.js中进行代理操作。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3