uni-app獲取位置經緯度並定位到當前位置
阿新 • • 發佈:2020-08-18
uni-app使用map元件定位到當前位置並進行標註
<template> <view> <map style="width: 100vw; height: 100vh;" :latitude="latitude" :longitude="longitude" :scale="scale" :markers="markers" ></map> </view> </template> <script> export default { data() { return { latitude: 39.909, // 預設定在首都 longitude: 116.39742, scale: 12, // 預設16 markers: [], markerHeight: 30, }; }, methods: { // 初次位置授權 getAuthorize() { return new Promise((resolve, reject) => { uni.authorize({ scope: "scope.userLocation", success: () => { resolve(); // 允許授權 }, fail: () => { reject(); // 拒絕授權 }, }); }); }, // 確認授權後,獲取使用者位置 getLocationInfo() { const that = this; uni.getLocation({ type: "gcj02", success: function (res) { // 暫時 that.longitude = res.longitude; //118.787575; that.latitude = res.latitude; //32.05024; that.markers = [ { id: "", latitude: res.latitude, longitude: res.longitude, iconPath: "../../static/mark.png", width: that.markerHeight, //寬 height: that.markerHeight, //高 }, ]; that.getList(); }, }); }, // 拒絕授權後,彈框提示是否手動開啟位置授權 openConfirm() { return new Promise((resolve, reject) => { uni.showModal({ title: "請求授權當前位置", content: "我們需要獲取地理位置資訊,為您推薦附近的美食", success: (res) => { if (res.confirm) { uni.openSetting().then((res) => { if (res[1].authSetting["scope.userLocation"] === true) { resolve(); // 開啟地圖許可權設定 } else { reject(); } }); } else if (res.cancel) { reject(); } }, }); }); }, // 徹底拒絕位置獲取 rejectGetLocation() { uni.showToast({ title: "你拒絕了授權,無法獲得周邊資訊", icon: "none", duration: 2000, }); }, getList() { console.log("獲取周圍美食"); }, }, onReady() { // wx請求獲取位置許可權 this.getAuthorize() .then(() => { // 同意後獲取 this.getLocationInfo(); }) .catch(() => { // 不同意給出彈框,再次確認 this.openConfirm() .then(() => { this.getLocationInfo(); }) .catch(() => { this.rejectGetLocation(); }); }); }, }; </script>