uniapp-地图定位

<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>

你可能感兴趣的:(javascript,前端,vue.js)