uni-app使用map組件定位到當前位置並進行標注
manifest.json添加如下內容:
需要定位的頁面
<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>