vue 获取用户位置 高德_Vue <调用高德获取地理位置问题>

这篇博客介绍了如何在Vue应用中使用vue-amap插件集成高德地图,通过AMap.Geolocation获取用户的位置信息,并展示了在组件中初始化定位及重新获取定位的方法。在获取到位置信息后,将坐标存储于sessionStorage中供后续使用。
摘要由CSDN通过智能技术生成

安装插件

首先npm install vue-amap --save

main.js代码:

import AMap from 'vue-amap';

Vue.use(AMap)

AMap.initAMapApiLoader({

key: '问后端要',

plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView',

'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor',

'AMap.CircleEditor', 'AMap.Geolocation']

});

vue页面代码:

export default {

data() {

let self = this;

return {

positions: {

lng: "",

lat: "",

address: "",

loaded: false

},

center: [121.59996, 31.197646],

plugin: [

{

pName: "Geolocation",

events: {

init(o) {

// o 是高德地图定位插件实例

o.getCurrentPosition((status, result) => {

console.log(result.position.lng,result.position.lat); // 能获取定位的所有信息

if (result && result.position) {

// self.str = result.formattedAddress;

// self.positions.address = self.str.substring(

// self.str.indexOf("市") + 1

// );

self.positions.lng = result.position.lng;

self.positions.lat = result.position.lat;

self.positions.loaded = true;

self.$nextTick();

// 把获取的数据提交到 store 的数据中,以便其他单文件组件使用

// self.$store.commit("POSITION", self.positions);

// console.log(self.positions);

sessionStorage.setItem(

"id",

JSON.stringify(

result.position.lng + "," + result.position.lat

)

);

}

});

}

}

}

]

};

},

mounted() {

console.log(window.sessionStorage.id) //可以获取到经纬度

}

}

重新获取定位方法:

//重新获取地理位置

getLocation() {

let self = this;

return new Promise((resolve, reject) => {

// sessionStorage中没有缓存,则开始定位

AMap.service(["AMap.Geolocation"], () => {

const geolocation = new AMap.Geolocation({

enableHighAccuracy: false, //是否使用高精度定位,默认:true

timeout: 5000 //超过5秒后停止定位,默认:无穷大

});

// 获取位置信息

geolocation.getCurrentPosition((status, result) => {

// console.log(result.position.lng,result.position.lat); // 能获取定位的所有信息

if (result && result.position) {

self.positions.lng = result.position.lng;

self.positions.lat = result.position.lat;

self.positions.loaded = true;

self.$nextTick();

// 把获取的数据提交到 store 的数据中,以便其他单文件组件使用

sessionStorage.setItem(

"id",

result.position.lng + "," + result.position.lat

);

}

});

// 获取位置信息完成触发事件

});

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值