• 小程序中腾讯位置服务的使用/小程序中使用腾讯服务获取位置信息


    1. 申请开发者密钥(key):申请密钥

    2. 开通webserviceAPI服务:控制台 -> key管理 -> 设置(使用该功能的key)-> 勾选webserviceAPI -> 保存

      (小程序SDK需要用到webserviceAPI的部分服务,所以使用该功能的KEY需要具备相应的权限)

    3. 下载微信小程序JavaScriptSDK,微信小程序JavaScriptSDK v1.1   JavaScriptSDK v1.2

    4. 安全域名设置,在小程序管理后台 -> 开发 -> 开发管理 -> 开发设置 -> “服务器域名” 中设置request合法域名,添加https://apis.map.qq.com

       详见腾讯位置服务开发者文档

      https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview

     项目内示例

      app.js

      

      globalData: {
        userInfo: {
          userId: '',  // 用户id
          userLevel: '',  // 会员等级
        },
        memberInfo: {
          vip: false
        },
        magicUrl: 'https://xxxx.com',
        imageDomain: 'https://imgxxxxxx/',
        host: 'https://xxxx.com', // 生产
        // host: 'https://test.xxx.com',  // 测试
        mapKey: 'MDIBZ-OZ6KU-REJV2-B5G46-HUJY7-IHFXS',
        aMapKey: 'f9bba16606e1ac804724872aa88df901', 
        sms_key: 'vgg8zrGR7R4kGrlV', //简单防止短信接口被刷,修改时需要与服务端代码配置一致,
      },

      utils 文件夹下map.js

    // 引入SDK核心类
    const QQMapWX = require('../libs/qqmap-wx-jssdk.min.js');
    const { regeneratorRuntime } = global
    // 实例化API核心类
    const MapWx = new QQMapWX({
      key: getApp().globalData.mapKey // 必填
    });
    
    
    
    //根据经纬度获取当前街道
    function reverseGeocoder(option) {
      return new Promise((resolve, reject) => {
        MapWx.reverseGeocoder({
          location: {
            latitude: option.latitude,
            longitude: option.longitude
          },
          get_poi:1,
          poi_options: 'policy=2;radius=2000;page_size=20;page_index=1',
          success: function (MapRes) {
            if (MapRes.status != 0) {
              errorShow('服务器错误,请联系管理员或重试');
              reject('服务器错误,请联系管理员或重试');
            }
            resolve(MapRes.result);
          },
          fail: function (MapRes) {
            errorShow('服务器错误,请联系管理员或重试');
            // reject(new Error('Network request failed'))
            reject(MapRes)
          },
          complete: function (MapRes) {
    
          }
        });
      })
    }
    
    //根据街道获取经纬度
    function geocoder(address) {
      return new Promise((resolve, reject) => {
        MapWx.geocoder({
          address: address,
          success: function (MapRes) {
            if (MapRes.status != 0) {
              errorShow('服务器错误,请联系管理员或重试');
              reject('服务器错误,请联系管理员或重试');
            }
            resolve(MapRes.result);
          },
          fail: function (MapRes) {
            errorShow('服务器错误,请联系管理员或重试');
            reject(new Error('Network request failed'))
          },
          complete: function (MapRes) {
    
          }
        });
      })
    }
    
    //计算一个点到多点的步行、驾车距离。option为坐标数组
    function calculateDistance(option) {
      return new Promise((resolve, reject) => {
        MapWx.calculateDistance({
          // mode: 'walking',
          mode: 'straight',
          from: option.from,
          to: option.to,
          success: function (res) {
            if(res.status=='0'){
              resolve(res.result.elements);
            }else{
              resolve(false);
            }
          },
          fail: function (res) {
            console.log(res)
            errorShow('服务器错误,请联系管理员或重试');
            reject(new Error('Network request failed'))
          },
          complete: function (res) {
            
          }
        });
      })
    }
    
    //计算一个点到另一个点的路径规划的骑行距离。option为坐标对象
    function direction(option) {
      return new Promise((resolve, reject) => {
        MapWx.direction({
          mode:'bicycling',
          from: option.from,
          to: option.to,
          success: function (res) {
            if(res.status=='0'){
              console.log(res)
              resolve(res.result.routes[0].distance);
            }else{
              resolve(false);
            }
          },
          fail: function (err) {
            // errorShow('服务器错误,请联系管理员或重试');
            // reject(new Error('Network request failed'))
            errorShow(err.message);
            reject(new Error(err.message))
          },
          complete: function (res) {
            
          }
        });
      })
    }
    
    function errorShow(title) {
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 1500
      })
    }
    
    function getSuggestion(option) {
      return new Promise((resolve, reject) => {
        MapWx.getSuggestion({
          keyword: option.keyword,
          region: option.city?option.city:'',
          policy: 1,
          region_fix: 1,
          success: function (res) {
            if (res.status == '0') {
              resolve(res.data);
            } else {
              resolve(false);
            }
          },
          fail: function (res) {
            errorShow('服务器错误,请联系管理员或重试');
            reject(new Error('Network request failed'))
          },
          complete: function (res) {
    
          }
        });
      })
    }
    
    module.exports = {
      reverseGeocoder: reverseGeocoder,
      calculateDistance: calculateDistance,
      direction: direction,
      getSuggestion: getSuggestion,
      geocoder: geocoder
    }

     utils.js中获取小程序位置方法

      

    //获取当前用户定位信息
    function getLocation() {
      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: 'gcj02', //返回可以用于wx.openLocation的经纬度
          success: res => {
            resolve(res);
          },
          fail: err => {
            resolve(err)
          }
        })
      })
    }

     注:可参考微信官方文档API

     https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.getLocation.html 

      

     map.js文件引入并使用

    const Util = require('../../utils/util.js');
    const Map = require('../../utils/map.js'); 
    const app = getApp()
    const {
    } = global
    
    
    Page({
        
         data:{
             useLocationAddress: '',
             iscacheAdr:false,
        },
          /*
       *,判断用户是否授权,如没有授权再次申请获取用户授权
       */
      getSetting() {
        wx.getSetting({
          success: res => {
            // console.log(res)
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                success(res) {
                  // 用户已经同意小程序使用位置信息,后续调用 wx.location 接口不会弹窗询问
                },
                fail() {
                  wx.showModal({
                    title: '',
                    content: '检测到您未打开地理位置权限,请前往开启',
                    showCancel: false,
                    success(res) {
                      if (res.confirm) {
                        wx.openSetting({
                          success(res) {
                            console.log(res.authSetting)
                          }
                        })
                      }
                    }
                  })
                }
              })
            }
          }
        })
      },
     //获取用户当前所在街道位置
      async getLocation() {
        try {
          let that = this;
            //微信官方文档API 获取经纬度
            let location = await Util.getLocation();
            if (location.latitude && location.longitude) {
              //存储当前坐标
              wx.setStorageSync('userLocation', location)
               //获取经纬度之后,使用腾讯位置服务接口
              let useLocation = await Map.reverseGeocoder(location);
              wx.setStorageSync('locatingProvince', useLocation.ad_info.province);
              wx.setStorageSync('locatingCity', useLocation.ad_info.city);
              app.globalData.city = useLocation.ad_info.city;
              console.log(app.globalData.city)
              if (!Util.checkCity()) {
                that.setData({
                  'openCity': false,
                  'useLocationAddress': useLocation.formatted_addresses.recommend,
                });
              } else {
                that.setData({
                  'openCity': true,
                  'useLocationAddress': useLocation.formatted_addresses.recommend,
                });
              }
              app.globalData.useLocation = useLocation;
              // 获取轮播图数据和首页商品数据
              that.getData();
            } else {
              wx.showModal({
                title: '',
                content: '定位失败,请检查网络环境或手机定位权限设置',
                cancelText: '手动定位',
                confirmText: '重新定位',
                success(res) {
                  if (res.confirm) {
                    that.getSetting();
                    that.getLocation();
                  } else if (res.cancel) {
                    wx.navigateTo({
                      url: '/pages/address/search/search'
                    })
                  }
                }
              })
            }
      
        } catch (err) {
          console.log(err)
        }
      },
       onshow:async function () {
        let globalLocation = app.globalData.useLocation;
        console.log('全局坐标:::' + globalLocation)
        console.log(this.data.useLocationAddress)
        // 判断是否在search页更改了地址
        if (options.cacheAdr) {
          this.setData({
            iscacheAdr: true
          })
        } else {
          wx.setStorageSync('selectAddress', '');
        }
        console.log('onshow用户是否选择了地址:::' + this.data.iscacheAdr)
        if ((Util.isEmpty(globalLocation)) || (this.data.useLocationAddress == "")) {
          console.log('onshow:::')
          this.getLocation();
        }
     }, 
    }) 

       wxml

    <navigator class="head-l skeleton-rect" url="/pages/address/search/search" hover-class='none'>
          <image class="icon" src="/assets/images/icon_site.png" mode="widthFix" />
          <text class="slh">{{useLocationAddress}}</text>
          <view class="arrow"></view>
     </navigator>
    
    
    /pages/address/search/search  为点击定位跳转定位搜索页
    useLocationAddress 为所获取的位置

      

     

  • 相关阅读:
    Reversing Encryption(模拟水题)
    Alphabetic Removals(模拟水题)
    Mishka and Contest(模拟水题)
    DFS中的奇偶剪枝(技巧)
    三分法搜索
    最短的包含字符串 (尺取)
    Android开发:最详细的 NavigationDrawer 开发实践总结
    Android开发:最详细的 Toolbar 开发实践总结
    Android开发:Translucent System Bar 的最佳实践
    Android微信智能心跳方案
  • 原文地址:https://www.cnblogs.com/shuihanxiao/p/14436643.html
Copyright © 2020-2023  润新知