当前位置:   article > 正文

在微信小程序中打开地图选择位置功能_微信小程序打开地图选择位置

微信小程序打开地图选择位置

前言

说真的,这是我第一次接触移动端的地图模块,一开始我真的一头雾水,感觉这个很难,但是通过不断的探索,在慢慢摸索中,一点一点搞懂了很多东西,还是很开心的,就想把我的经验分享给大家。希望能帮助到你们~

首先查看效果

需要用户授权,才能拿到当前位置。如果用户拒绝后,再次点击选择位置,将会提示重新授权,引导用户开启权限
需要用户授权,才能拿到当前位置

如果用户拒绝后,再次点击选择位置
将会提示重新授权,引导用户开启权限
授权成功后获取到位置的名字,显示出来,这里用wx.getLocation只能拿到经纬度,我这里是使用了腾讯位置服务的API拿到位置名称的,先上图授权成功后获取到位置的名字,显示出来
搜索位置
选择位置

选好了起点和终点

一、准备工作

1-1. 下载小程序地理定位qqmap-wx-jssdk.js

在这里插入图片描述

1-2. 放在项目中的utils文件夹下面;

在这里插入图片描述

1-3. 在utils 文件夹中,创建location-util.js文件

getLocation()方法是获取用户地理位置的,需要用户授权
chooseLocation()方法是打开微信内置地图,供用户选择位置的

location-util.js

var util = require('util.js');

function getLocation() {
  return new Promise(function (resolve, reject) {
    wx.getSetting({
      success: (res) => {
        //console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] === false) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                });
                getCurrentLocation(resolve, reject);
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权,调用wx.getLocation的API
                      getCurrentLocation(resolve, reject);
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      });
                      getCurrentLocation(resolve, reject);
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() { //用户同意开启授权
              //进行地理位置授权完成后的逻辑操作
              getCurrentLocation(resolve, reject);
            },
            fail(res) { //用户拒绝开启授权
              wx.hideLoading()
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 2000
              });
              getCurrentLocation(resolve, reject);
            }
          })
        } else if (res.authSetting['scope.userLocation'] == true) {
          getCurrentLocation(resolve, reject);
        }
      }
    });
  });
}


function getCurrentLocation(resolve, reject) {
  wx.getLocation({
    // type: 'gcj02',
    type: 'wgs84',
    success: function (res) {
      var longitude = res.longitude //经度
      var latitude = res.latitude //纬度
      wx.setStorageSync("longitude", longitude);
      wx.setStorageSync("latitude", latitude);
      if (resolve) {
        resolve(res);
      }
    },
    fail: function (res) { 
      //用户授权获取地理位置失败,默认怀化市鹤城区人民政府 
      res = {longitude:110.040001,latitude:27.57862};
      if (resolve) {
         resolve(res);
      }
    }
  })  
}

// 打开地图选择位置
function chooseLocation() {
	var that = this;
    return new Promise(function (resolve, reject) {
        that.getLocation().then(res => {
            if (res) {
              wx.chooseLocation({
                latitude: res.latitude,
                longitude: res.longitude,
                success: function (addressInfo) {
                  resolve(addressInfo);
                },
                fail: function (res) {
                  reject(res);
                }
              });
            } else {
              util.showMsg('定位失败');
            }
        });
    });
}

/**
 * 导出
 */
module.exports = {
  getLocation: getLocation,
  chooseLocation: chooseLocation,
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126

1-4. 在 util.js 文件中,添加如下代码;

在这里插入图片描述

util.js

const showMsg = (msg, icon) => {
    if (isBlank(icon)) {
      icon = "none";
    }
    wx.showToast({
      title: msg,
      icon: icon,
      duration: 2000
    })
}
module.exports = {
    showMsg: showMsg,
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

二、页面代码

以下代码全部都是.js文件页面中的代码
在这里插入图片描述
map-navigation.js文件中

2-1.引入文件

// 引入工具类
const locationUtil = require("../../utils/location-util")
// 引入SDK核心类
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
  • 1
  • 2
  • 3
  • 4

2-2.data中的数据

    data: {
        // 切换导航栏
        actionbarNumber: 1,
        // 起点经纬度
        startLatitude: '',
        startLongitude: '',
        // 起点
        startAddress:'',
        // 终点
        destination: ''
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2-3.使用封装好的地图工具

	// 获取用户位置,但是只有经纬度,没有位置的名称
    handleLoacation:function(){
        locationUtil.getLocation().then(res => {
            console.log("获取用户位置:",res);
            var params = {lng:res.longitude,lat:res.latitude};
            console.log(params.lng);
        });
    },
    // 用户选择地图,可以获取到位置的经纬度和名称等信息
    handleAddress:function(){
        locationUtil.chooseLocation().then(res => {
        	console.log("选择的位置信息:",res);
            var params = {lng:res.longitude,lat:res.latitude};
            this.setData({
                destination: res.name
            })
        });  
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

打印的结果
在这里插入图片描述

2-4.用腾讯地图API获取用户授权位置的地点名称

在这里插入图片描述

要注意引用核心类,我前面是有引用的

    // 获取当前位置信息
    getAddressName: function () {
        var that = this
        // 实例化腾讯地图API核心类
        const qqmapsdk = new QQMapWX({
          key: '开发密钥' // 必填
        });
        //1、获取当前位置坐标
        wx.getLocation({
          type: 'wgs84',
          success: function (res) {
              that.setData({
                  	startLatitude: res.latitude,
                 	startLongitude: res.longitude,
              })
            //2、根据坐标获取当前位置名称,显示在顶部:腾讯地图逆地址解析
            qqmapsdk.reverseGeocoder({
              location: {
	               latitude: res.latitude,
	               longitude: res.longitude
              },
              success: function (addressRes) {
                var address = addressRes.result.formatted_addresses.recommend;
                // 位置的名字
                that.setData({
                    startAddress: address
                })
              }
            })
          }
        })
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

三、到这里就实现了用户授权位置,拿到位置的名称和打开地图选择位置这个功能哟

3-1.跟大家说一下我做这个的时候踩到的一个坑吧

就是我写完以上的代码后,在模拟器上面跑是没有任何问题的,但是在真机上运行就没有反应,后来我查阅资料后发现是我没有在全局文件app.json中加入配置,大家一定要引以为戒呀!!!记得加上这个配置
在这里插入图片描述

    "permission": {
        "scope.userLocation": {
            "desc": "用于获取当前定位,查询附近门店"
        }
    },
    "requiredPrivateInfos": [
        "getLocation",
        "chooseLocation"
    ],
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3-2.再多句嘴,温馨提示一下,为避免影响获取地理位置正常使用,微信公众开发平台的接口也要去申请喔。

在“开发”—>“开发管理”下面的“接口设置”------>"地理位置"需要申请wx.getLocation和wx.chooseLocation的使用
一般来说,按正常的流程去申请是没什么问题的。

在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/889325
推荐阅读
相关标签
  

闽ICP备14008679号