uniapp 小程序地图定位选点功能

<template></template>
<script>
import { getAddressCode } from "@/api/address";
import config from '@/config/config'
export default {
  data() {
    return {
      config
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    // 初始化地图并且调用
    initMap() {
      let that = this;
      uni.chooseLocation({
        success: function (res) {
          /**获取地址详情地址 */
          that.posToCity(res.latitude, res.longitude).then((val) => {
            /**获取地址code */
            getAddressCode(
              val.regeocode.addressComponent.citycode,
              val.regeocode.addressComponent.township
            ).then((code) => {
              that.$emit("callback", { ...val, ...res, ...code });
              that.$emit("close");
            });
          });
        },
        fail() {
          that.$emit("close");
        },
      });
    },

    // 根据当前客户端判断展示不同类型数据
    init() {
      // #ifdef MP-WEIXIN
      this.wechatMap();
      // #endif
      // #ifndef MP-WEIXIN
      this.initMap();
      // #endif
    },

    // 如果是微信小程序单独走微信小程序授权模式
    wechatMap() {
      let that = this;
      uni.authorize({
        scope: "scope.userLocation",
        success() {
          // 允许授权
          that.initMap();
        },
        fail() {
          //拒绝授权
          uni.showModal({
            content: "检测到您没打开获取地址功能权限,是否去设置打开?",
            confirmText: "确认",
            cancelText: "取消",
            success: (res) => {
              if (res.confirm) {
                // 打开设置好后重新刷新地图
                uni.openSetting({
                  success: (res) => {
                    that.initMap();
                  },
                });
              } else {
                // 取消后关闭
                that.$emit("close");
                return false;
              }
            },
          });
          return false;
        },
      });
    },
    // 获取城市的数据
    posToCity(latitude, longitude) {
      return new Promise((resolve, reject) => {
        uni.request({
        //这个api是高德的api 需要配置高德apikey 
          url: `https://restapi.amap.com/v3/geocode/regeo`,
          method: "GET",
          data: {
            key: config.aMapKey, //web服务的key
            location: `${longitude},${latitude}`,
          },
          success: ({ data }) => {
            const { status, info } = data;
            if (status === "1") {
              resolve(data);
            } else {
              reject(info);
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
</style>

 

效果图如下

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值