• uni-app 使用uni.getLocation获取经纬度配合腾讯地图api获取当前地址


    前言

    • 最近在开发中需要根据经纬度获取当前位置信息,传递给后端,用来回显显示当前位置

    • 查阅uni-app文档,发现uni.getLocation () 可以获取到经纬度,但是在小程序环境没有地址信息

    • 思考怎么把经纬度换成地址,如果经纬度是key,那地址就是value,第三方地图就是数据库

    • 所以我们只要使用uni.getLocation ()获取经纬度配合地图api就可以解决这个需求

    报错情况-对应解决办法

    报错一:没有在用户隐私指引中获取当前位置权限
    报错二:"errMsg": "getLocation:fail fail:require permission desc"
    解决方案:在manifest.json-微信小程序配置-位置接口打勾-填写用途

    或者直接源码视图-小程序直接配置如下代码
    1. "permission" : {
    2.           "scope.userLocation" : {
    3.               "desc" : "真实用途"
    4.           }
    5. }
    报错三:ferrMsg: "getlocation;fail the api heed to be declared in the requiredprivateInfosfield in app.json/ext.json"
    解决方案:小程序源码视图添加如下代码
    "requiredPrivateInfos" : [ "getLocation" ],
    总结:
    • 报错一是因为微信小程序官方最近必须对相应api进行权限申请,询问用户。

    • 报错二是询问用户是否愿意获取当前位置信息

    • 报错三是用户同意之后,使用相关8个地理位置相关接口时,需要声明该字段,否则将无法正常使用

    • 一般用户隐私指引没问题,报错二三使用勾选方式,就会在源码视图帮我们生成对应代码,不会有问题

    uni.getLocation ()为什么获取不到位置信息

    • 官方文档说的很清楚,只用在APP环境下,这个api才会有位置信息,小程序环境只有经纬度

    为什么使用腾讯地图配合uni.getLocation ()来实现

    • 因为uni-app提供的官方地图就是腾讯地图

    • 并且uni.getLocation ()的type='gcz02'时经纬度在腾讯地图可以直接使用

    • 并不是只能用腾讯地图,而是只是获取一个位置信息,这样使用更方便省去很多麻烦

    代码实现

    1.在腾讯地图注册账号,获取key,下载SDK参考文章:uni-app 小程序使用腾讯地图完成搜索功能

    高德地图原生SDK:微信小程序JavaScript SDK | 腾讯位置服务

    SDK可以随便下一个

    2.在uni-app/utils/建立tenxun文件夹/下面放我们下载sdk文件( qqmap-wx-jssdk.js)代码如下
    1. /**
    2. * 微信小程序JavaScriptSDK
    3. *
    4. * @version 1.1
    5. * @date 2019-01-20
    6. */
    7. var ERROR_CONF = {
    8.   KEY_ERR: 311,
    9.   KEY_ERR_MSG: 'key格式错误',
    10.   PARAM_ERR: 310,
    11.   PARAM_ERR_MSG: '请求参数信息有误',
    12.   SYSTEM_ERR: 600,
    13.   SYSTEM_ERR_MSG: '系统错误',
    14.   WX_ERR_CODE: 1000,
    15.   WX_OK_CODE: 200
    16. };
    17. var BASE_URL = 'https://apis.map.qq.com/ws/';
    18. var URL_SEARCH = BASE_URL + 'place/v1/search';
    19. var URL_SUGGESTION = BASE_URL + 'place/v1/suggestion';
    20. var URL_GET_GEOCODER = BASE_URL + 'geocoder/v1/';
    21. var URL_CITY_LIST = BASE_URL + 'district/v1/list';
    22. var URL_AREA_LIST = BASE_URL + 'district/v1/getchildren';
    23. var URL_DISTANCE = BASE_URL + 'distance/v1/';
    24. var EARTH_RADIUS = 6378136.49;
    25. var Utils = {
    26.   /**
    27.     * 得到终点query字符串
    28.     * @param {Array|String} 检索数据
    29.     */
    30.   location2query(data) {
    31.       if (typeof data == 'string') {
    32.           return data;
    33.       }
    34.       var query = '';
    35.       for (var i = 0; i < data.length; i++) {
    36.           var d = data[i];
    37.           if (!!query) {
    38.               query += ';';
    39.           }
    40.           if (d.location) {
    41.               query = query + d.location.lat + ',' + d.location.lng;
    42.           }
    43.           if (d.latitude && d.longitude) {
    44.               query = query + d.latitude + ',' + d.longitude;
    45.           }
    46.       }
    47.       return query;
    48.   },
    49.   /**
    50.     * 计算角度
    51.     */
    52.   rad(d) {
    53.     return d * Math.PI / 180.0;
    54.   },  
    55.   /**
    56.     * 处理终点location数组
    57.     * @return 返回终点数组
    58.     */
    59.   getEndLocation(location){
    60.     var to = location.split(';');
    61.     var endLocation = [];
    62.     for (var i = 0; i < to.length; i++) {
    63.       endLocation.push({
    64.         lat: parseFloat(to[i].split(',')[0]),
    65.         lng: parseFloat(to[i].split(',')[1])
    66.       })
    67.     }
    68.     return endLocation;
    69.   },
    70.   /**
    71.     * 计算两点间直线距离
    72.     * @param a 表示纬度差
    73.     * @param b 表示经度差
    74.     * @return 返回的是距离,单位m
    75.     */
    76.   getDistance(latFrom, lngFrom, latTo, lngTo) {
    77.     var radLatFrom = this.rad(latFrom);
    78.     var radLatTo = this.rad(latTo);
    79.     var a = radLatFrom - radLatTo;
    80.     var b = this.rad(lngFrom) - this.rad(lngTo);
    81.     var distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLatFrom) * Math.cos(radLatTo) * Math.pow(Math.sin(b / 2), 2)));
    82.     distance = distance * EARTH_RADIUS;
    83.     distance = Math.round(distance * 10000) / 10000;
    84.     return parseFloat(distance.toFixed(0));
    85.   },
    86.   /**
    87.     * 使用微信接口进行定位
    88.     */
    89.   getWXLocation(success, fail, complete) {
    90.       wx.getLocation({
    91.           type: 'gcj02',
    92.           success: success,
    93.           fail: fail,
    94.           complete: complete
    95.       });
    96.   },
    97.   /**
    98.     * 获取location参数
    99.     */
    100.   getLocationParam(location) {
    101.       if (typeof location == 'string') {
    102.           var locationArr = location.split(',');
    103.           if (locationArr.length === 2) {
    104.               location = {
    105.                   latitude: location.split(',')[0],
    106.                   longitude: location.split(',')[1]
    107.               };
    108.           } else {
    109.               location = {};
    110.           }
    111.       }
    112.       return location;
    113.   },
    114.   /**
    115.     * 回调函数默认处理
    116.     */
    117.   polyfillParam(param) {
    118.       param.success = param.success || function () { };
    119.       param.fail = param.fail || function () { };
    120.       param.complete = param.complete || function () { };
    121.   },
    122.   /**
    123.     * 验证param对应的key值是否为空
    124.     *
    125.     * @param {Object} param 接口参数
    126.     * @param {String} key 对应参数的key
    127.     */
    128.   checkParamKeyEmpty(param, key) {
    129.       if (!param[key]) {
    130.           var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + key +'参数格式有误');
    131.           param.fail(errconf);
    132.           param.complete(errconf);
    133.           return true;
    134.       }
    135.       return false;
    136.   },
    137.   /**
    138.     * 验证参数中是否存在检索词keyword
    139.     *
    140.     * @param {Object} param 接口参数
    141.     */
    142.   checkKeyword(param){
    143.       return !this.checkParamKeyEmpty(param, 'keyword');
    144.   },
    145.   /**
    146.     * 验证location值
    147.     *
    148.     * @param {Object} param 接口参数
    149.     */
    150.   checkLocation(param) {
    151.       var location = this.getLocationParam(param.location);
    152.       if (!location || !location.latitude || !location.longitude) {
    153.           var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + ' location参数格式有误');
    154.           param.fail(errconf);
    155.           param.complete(errconf);
    156.           return false;
    157.       }
    158.       return true;
    159.   },
    160.   /**
    161.     * 构造错误数据结构
    162.     * @param {Number} errCode 错误码
    163.     * @param {Number} errMsg 错误描述
    164.     */
    165.   buildErrorConfig(errCode, errMsg) {
    166.       return {
    167.           status: errCode,
    168.           message: errMsg
    169.       };
    170.   },
    171.   /**
    172.     *
    173.     * 数据处理函数
    174.     * 根据传入参数不同处理不同数据
    175.     * @param {String} feature 功能名称
    176.     * search 地点搜索
    177.     * suggest关键词提示
    178.     * reverseGeocoder逆地址解析
    179.     * geocoder地址解析
    180.     * getCityList获取城市列表:父集
    181.     * getDistrictByCityId获取区县列表:子集
    182.     * calculateDistance距离计算
    183.     * @param {Object} param 接口参数
    184.     * @param {Object} data 数据
    185.     */
    186.   handleData(param,data,feature){
    187.     if (feature === 'search') {
    188.       var searchResult = data.data;
    189.       var searchSimplify = [];
    190.       for (var i = 0; i < searchResult.length; i++) {
    191.         searchSimplify.push({
    192.           id: searchResult[i].id || null,
    193.           title: searchResult[i].title || null,
    194.           latitude: searchResult[i].location && searchResult[i].location.lat || null,
    195.           longitude: searchResult[i].location && searchResult[i].location.lng || null,
    196.           address: searchResult[i].address || null,
    197.           category: searchResult[i].category || null,
    198.           tel: searchResult[i].tel || null,
    199.           adcode: searchResult[i].ad_info && searchResult[i].ad_info.adcode || null,
    200.           city: searchResult[i].ad_info && searchResult[i].ad_info.city || null,
    201.           district: searchResult[i].ad_info && searchResult[i].ad_info.district || null,
    202.           province: searchResult[i].ad_info && searchResult[i].ad_info.province || null
    203.         })
    204.       }
    205.       param.success(data, {
    206.         searchResult: searchResult,
    207.         searchSimplify: searchSimplify
    208.       })
    209.     } else if (feature === 'suggest') {
    210.       var suggestResult = data.data;
    211.       var suggestSimplify = [];
    212.       for (var i = 0; i < suggestResult.length; i++) {
    213.         suggestSimplify.push({
    214.           adcode: suggestResult[i].adcode || null,
    215.           address: suggestResult[i].address || null,
    216.           category: suggestResult[i].category || null,
    217.           city: suggestResult[i].city || null,
    218.           district: suggestResult[i].district || null,
    219.           id: suggestResult[i].id || null,
    220.           latitude: suggestResult[i].location && suggestResult[i].location.lat || null,
    221.           longitude: suggestResult[i].location && suggestResult[i].location.lng || null,
    222.           province: suggestResult[i].province || null,
    223.           title: suggestResult[i].title || null,
    224.           type: suggestResult[i].type || null
    225.         })
    226.       }
    227.       param.success(data, {
    228.         suggestResult: suggestResult,
    229.         suggestSimplify: suggestSimplify
    230.         })
    231.     } else if (feature === 'reverseGeocoder') {
    232.       var reverseGeocoderResult = data.result;
    233.       var reverseGeocoderSimplify = {
    234.         address: reverseGeocoderResult.address || null,
    235.         latitude: reverseGeocoderResult.location && reverseGeocoderResult.location.lat || null,
    236.         longitude: reverseGeocoderResult.location && reverseGeocoderResult.location.lng || null,
    237.         adcode: reverseGeocoderResult.ad_info && reverseGeocoderResult.ad_info.adcode || null,
    238.         city: reverseGeocoderResult.address_component && reverseGeocoderResult.address_component.city || null,
    239.         district: reverseGeocoderResult.address_component && reverseGeocoderResult.address_component.district || null,
    240.         nation: reverseGeocoderResult.address_component && reverseGeocoderResult.address_component.nation || null,
    241.         province: reverseGeocoderResult.address_component && reverseGeocoderResult.address_component.province || null,
    242.         street: reverseGeocoderResult.address_component && reverseGeocoderResult.address_component.street || null,
    243.         street_number: reverseGeocoderResult.address_component && reverseGeocoderResult.address_component.street_number || null,
    244.         recommend: reverseGeocoderResult.formatted_addresses && reverseGeocoderResult.formatted_addresses.recommend || null,
    245.         rough: reverseGeocoderResult.formatted_addresses && reverseGeocoderResult.formatted_addresses.rough || null
    246.       };
    247.       if (reverseGeocoderResult.pois) {//判断是否返回周边poi
    248.         var pois = reverseGeocoderResult.pois;
    249.         var poisSimplify = [];
    250.         for (var i = 0;i < pois.length;i++) {
    251.           poisSimplify.push({
    252.             id: pois[i].id || null,
    253.             title: pois[i].title || null,
    254.             latitude: pois[i].location && pois[i].location.lat || null,
    255.             longitude: pois[i].location && pois[i].location.lng || null,
    256.             address: pois[i].address || null,
    257.             category: pois[i].category || null,
    258.             adcode: pois[i].ad_info && pois[i].ad_info.adcode || null,
    259.             city: pois[i].ad_info && pois[i].ad_info.city || null,
    260.             district: pois[i].ad_info && pois[i].ad_info.district || null,
    261.             province: pois[i].ad_info && pois[i].ad_info.province || null
    262.           })
    263.         }
    264.         param.success(data,{
    265.           reverseGeocoderResult: reverseGeocoderResult,
    266.           reverseGeocoderSimplify: reverseGeocoderSimplify,
    267.           pois: pois,
    268.           poisSimplify: poisSimplify
    269.         })
    270.       } else {
    271.         param.success(data, {
    272.           reverseGeocoderResult: reverseGeocoderResult,
    273.           reverseGeocoderSimplify: reverseGeocoderSimplify
    274.         })
    275.       }
    276.     } else if (feature === 'geocoder') {
    277.       var geocoderResult = data.result;
    278.       var geocoderSimplify = {
    279.         title: geocoderResult.title || null,
    280.         latitude: geocoderResult.location && geocoderResult.location.lat || null,
    281.         longitude: geocoderResult.location && geocoderResult.location.lng || null,
    282.         adcode: geocoderResult.ad_info && geocoderResult.ad_info.adcode || null,
    283.         province: geocoderResult.address_components && geocoderResult.address_components.province || null,
    284.         city: geocoderResult.address_components && geocoderResult.address_components.city || null,
    285.         district: geocoderResult.address_components && geocoderResult.address_components.district || null,
    286.         street: geocoderResult.address_components && geocoderResult.address_components.street || null,
    287.         street_number: geocoderResult.address_components && geocoderResult.address_components.street_number || null,
    288.         level: geocoderResult.level || null
    289.       };
    290.       param.success(data,{
    291.         geocoderResult: geocoderResult,
    292.         geocoderSimplify: geocoderSimplify
    293.       });
    294.     } else if (feature === 'getCityList') {
    295.       var provinceResult = data.result[0];
    296.       var cityResult = data.result[1];
    297.       var districtResult = data.result[2];
    298.       param.success(data,{
    299.         provinceResult: provinceResult,
    300.         cityResult: cityResult,
    301.         districtResult: districtResult
    302.       });
    303.     } else if (feature === 'getDistrictByCityId') {
    304.       var districtByCity = data.result[0];
    305.       param.success(data, districtByCity);
    306.     } else if (feature === 'calculateDistance') {
    307.       var calculateDistanceResult = data.result.elements;  
    308.       var distance = [];
    309.       for (var i = 0; i < calculateDistanceResult.length; i++){
    310.         distance.push(calculateDistanceResult[i].distance);
    311.       }  
    312.       param.success(data, {
    313.         calculateDistanceResult: calculateDistanceResult,
    314.         distance: distance
    315.         });
    316.     } else {
    317.       param.success(data);
    318.     }
    319.   },
    320.   /**
    321.     * 构造微信请求参数,公共属性处理
    322.     *
    323.     * @param {Object} param 接口参数
    324.     * @param {Object} param 配置项
    325.     * @param {String} feature 方法名
    326.     */
    327.   buildWxRequestConfig(param, options, feature) {
    328.       var that = this;
    329.       options.header = { "content-type": "application/json" };
    330.       options.method = 'GET';
    331.       options.success = function (res) {
    332.           var data = res.data;
    333.           if (data.status === 0) {
    334.             that.handleData(param, data, feature);
    335.           } else {
    336.               param.fail(data);
    337.           }
    338.       };
    339.       options.fail = function (res) {
    340.           res.statusCode = ERROR_CONF.WX_ERR_CODE;
    341.           param.fail(that.buildErrorConfig(ERROR_CONF.WX_ERR_CODE, res.errMsg));
    342.       };
    343.       options.complete = function (res) {
    344.           var statusCode = +res.statusCode;
    345.           switch(statusCode) {
    346.               case ERROR_CONF.WX_ERR_CODE: {
    347.                   param.complete(that.buildErrorConfig(ERROR_CONF.WX_ERR_CODE, res.errMsg));
    348.                   break;
    349.               }
    350.               case ERROR_CONF.WX_OK_CODE: {
    351.                   var data = res.data;
    352.                   if (data.status === 0) {
    353.                       param.complete(data);
    354.                   } else {
    355.                       param.complete(that.buildErrorConfig(data.status, data.message));
    356.                   }
    357.                   break;
    358.               }
    359.               default:{
    360.                   param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, ERROR_CONF.SYSTEM_ERR_MSG));
    361.               }
    362.           }
    363.       };
    364.       return options;
    365.   },
    366.   /**
    367.     * 处理用户参数是否传入坐标进行不同的处理
    368.     */
    369.   locationProcess(param, locationsuccess, locationfail, locationcomplete) {
    370.       var that = this;
    371.       locationfail = locationfail || function (res) {
    372.           res.statusCode = ERROR_CONF.WX_ERR_CODE;
    373.           param.fail(that.buildErrorConfig(ERROR_CONF.WX_ERR_CODE, res.errMsg));
    374.       };
    375.       locationcomplete = locationcomplete || function (res) {
    376.           if (res.statusCode == ERROR_CONF.WX_ERR_CODE) {
    377.               param.complete(that.buildErrorConfig(ERROR_CONF.WX_ERR_CODE, res.errMsg));
    378.           }
    379.       };
    380.       if (!param.location) {
    381.           that.getWXLocation(locationsuccess, locationfail, locationcomplete);
    382.       } else if (that.checkLocation(param)) {
    383.           var location = Utils.getLocationParam(param.location);
    384.           locationsuccess(location);
    385.       }
    386.   }
    387. };
    388. class QQMapWX {
    389.   /**
    390.     * 构造函数
    391.     *
    392.     * @param {Object} options 接口参数,key 为必选参数
    393.     */
    394.   constructor(options) {
    395.       if (!options.key) {
    396.           throw Error('key值不能为空');
    397.       }
    398.       this.key = options.key;
    399.   };
    400.   /**
    401.     * POI周边检索
    402.     *
    403.     * @param {Object} options 接口参数对象
    404.     *
    405.     * 参数对象结构可以参考
    406.     * @see http://lbs.qq.com/webservice_v1/guide-search.html
    407.     */
    408.   search(options) {
    409.       var that = this;
    410.       options = options || {};
    411.       Utils.polyfillParam(options);
    412.       if (!Utils.checkKeyword(options)) {
    413.           return;
    414.       }
    415.       var requestParam = {
    416.           keyword: options.keyword,
    417.           orderby: options.orderby || '_distance',
    418.           page_size: options.page_size || 10,
    419.           page_index: options.page_index || 1,
    420.           output: 'json',
    421.           key: that.key
    422.       };
    423.       if (options.address_format) {
    424.           requestParam.address_format = options.address_format;
    425.       }
    426.       if (options.filter) {
    427.           requestParam.filter = options.filter;
    428.       }
    429.       var distance = options.distance || "1000";
    430.       var auto_extend = options.auto_extend || 1;
    431.       var region = null;
    432.       var rectangle = null;
    433.       //判断城市限定参数
    434.       if (options.region) {
    435.         region = options.region;
    436.       }
    437.       //矩形限定坐标(暂时只支持字符串格式)
    438.       if (options.rectangle) {
    439.         rectangle = options.rectangle;
    440.       }
    441.       var locationsuccess = function (result) {        
    442.         if (region && !rectangle) {
    443.           //城市限定参数拼接
    444.           requestParam.boundary = "region(" + region + "," + auto_extend + "," + result.latitude + "," + result.longitude + ")";
    445.         } else if (rectangle && !region) {
    446.           //矩形搜索
    447.           requestParam.boundary = "rectangle(" + rectangle + ")";
    448.           } else {
    449.             requestParam.boundary = "nearby(" + result.latitude + "," + result.longitude + "," + distance + "," + auto_extend + ")";
    450.           }            
    451.           wx.request(Utils.buildWxRequestConfig(options, {
    452.               url: URL_SEARCH,
    453.               data: requestParam
    454.           }, 'search'));
    455.       };
    456.       Utils.locationProcess(options, locationsuccess);
    457.   };
    458.   /**
    459.     * sug模糊检索
    460.     *
    461.     * @param {Object} options 接口参数对象
    462.     *
    463.     * 参数对象结构可以参考
    464.     * http://lbs.qq.com/webservice_v1/guide-suggestion.html
    465.     */
    466.   getSuggestion(options) {
    467.       var that = this;
    468.       options = options || {};
    469.       Utils.polyfillParam(options);
    470.       if (!Utils.checkKeyword(options)) {
    471.           return;
    472.       }
    473.       var requestParam = {
    474.           keyword: options.keyword,
    475.           region: options.region || '全国',
    476.           region_fix: options.region_fix || 0,
    477.           policy: options.policy || 0,
    478.           page_size: options.page_size || 10,//控制显示条数
    479.           page_index: options.page_index || 1,//控制页数
    480.           get_subpois : options.get_subpois || 0,//返回子地点
    481.           output: 'json',
    482.           key: that.key
    483.       };
    484.       //长地址
    485.       if (options.address_format) {
    486.         requestParam.address_format = options.address_format;
    487.       }
    488.       //过滤
    489.       if (options.filter) {
    490.         requestParam.filter = options.filter;
    491.       }
    492.       //排序
    493.       if (options.location) {
    494.         var locationsuccess = function (result) {
    495.           requestParam.location = result.latitude + ',' + result.longitude;
    496.           wx.request(Utils.buildWxRequestConfig(options, {
    497.             url: URL_SUGGESTION,
    498.             data: requestParam
    499.           }, "suggest"));      
    500.         };
    501.         Utils.locationProcess(options, locationsuccess);
    502.       } else {
    503.         wx.request(Utils.buildWxRequestConfig(options, {
    504.           url: URL_SUGGESTION,
    505.           data: requestParam
    506.         }, "suggest"));      
    507.       }
    508.   };
    509.   /**
    510.     * 逆地址解析
    511.     *
    512.     * @param {Object} options 接口参数对象
    513.     *
    514.     * 请求参数结构可以参考
    515.     * http://lbs.qq.com/webservice_v1/guide-gcoder.html
    516.     */
    517.   reverseGeocoder(options) {
    518.       var that = this;
    519.       options = options || {};
    520.       Utils.polyfillParam(options);
    521.       var requestParam = {
    522.           coord_type: options.coord_type || 5,
    523.           get_poi: options.get_poi || 0,
    524.           output: 'json',
    525.           key: that.key
    526.       };
    527.       if (options.poi_options) {
    528.           requestParam.poi_options = options.poi_options
    529.       }
    530.       var locationsuccess = function (result) {
    531.           requestParam.location = result.latitude + ',' + result.longitude;
    532.           wx.request(Utils.buildWxRequestConfig(options, {
    533.               url: URL_GET_GEOCODER,
    534.               data: requestParam
    535.           }, 'reverseGeocoder'));
    536.       };
    537.       Utils.locationProcess(options, locationsuccess);
    538.   };
    539.   /**
    540.     * 地址解析
    541.     *
    542.     * @param {Object} options 接口参数对象
    543.     *
    544.     * 请求参数结构可以参考
    545.     * http://lbs.qq.com/webservice_v1/guide-geocoder.html
    546.     */
    547.   geocoder(options) {
    548.       var that = this;
    549.       options = options || {};
    550.       Utils.polyfillParam(options);
    551.       if (Utils.checkParamKeyEmpty(options, 'address')) {
    552.           return;
    553.       }
    554.       var requestParam = {
    555.           address: options.address,
    556.           output: 'json',
    557.           key: that.key
    558.       };
    559.       //城市限定
    560.       if (options.region) {
    561.         requestParam.region = options.region;
    562.       }
    563.       wx.request(Utils.buildWxRequestConfig(options, {
    564.           url: URL_GET_GEOCODER,
    565.           data: requestParam
    566.       },'geocoder'));
    567.   };
    568.   /**
    569.     * 获取城市列表
    570.     *
    571.     * @param {Object} options 接口参数对象
    572.     *
    573.     * 请求参数结构可以参考
    574.     * http://lbs.qq.com/webservice_v1/guide-region.html
    575.     */
    576.   getCityList(options) {
    577.       var that = this;
    578.       options = options || {};
    579.       Utils.polyfillParam(options);
    580.       var requestParam = {
    581.           output: 'json',
    582.           key: that.key
    583.       };
    584.       wx.request(Utils.buildWxRequestConfig(options, {
    585.           url: URL_CITY_LIST,
    586.           data: requestParam
    587.       },'getCityList'));
    588.   };
    589.   /**
    590.     * 获取对应城市ID的区县列表
    591.     *
    592.     * @param {Object} options 接口参数对象
    593.     *
    594.     * 请求参数结构可以参考
    595.     * http://lbs.qq.com/webservice_v1/guide-region.html
    596.     */
    597.   getDistrictByCityId(options) {
    598.       var that = this;
    599.       options = options || {};
    600.       Utils.polyfillParam(options);
    601.       if (Utils.checkParamKeyEmpty(options, 'id')) {
    602.           return;
    603.       }
    604.       var requestParam = {
    605.           id: options.id || '',
    606.           output: 'json',
    607.           key: that.key
    608.       };
    609.       wx.request(Utils.buildWxRequestConfig(options, {
    610.           url: URL_AREA_LIST,
    611.           data: requestParam
    612.       },'getDistrictByCityId'));
    613.   };
    614.   /**
    615.     * 用于单起点到多终点的路线距离(非直线距离)计算:
    616.     * 支持两种距离计算方式:步行和驾车。
    617.     * 起点到终点最大限制直线距离10公里。
    618.     *
    619.     * 新增直线距离计算。
    620.     *
    621.     * @param {Object} options 接口参数对象
    622.     *
    623.     * 请求参数结构可以参考
    624.     * http://lbs.qq.com/webservice_v1/guide-distance.html
    625.     */
    626.   calculateDistance(options) {
    627.       var that = this;
    628.       options = options || {};
    629.       Utils.polyfillParam(options);
    630.       if (Utils.checkParamKeyEmpty(options, 'to')) {
    631.           return;
    632.       }
    633.       var requestParam = {
    634.           mode: options.mode || 'walking',
    635.           to: Utils.location2query(options.to),
    636.           output: 'json',
    637.           key: that.key
    638.       };
    639.       if (options.from) {
    640.         options.location = options.from;
    641.       }
    642.       //计算直线距离
    643.       if(requestParam.mode == 'straight'){        
    644.         var locationsuccess = function (result) {
    645.           var locationTo = Utils.getEndLocation(requestParam.to);//处理终点坐标
    646.           var data = {
    647.             message:"query ok",
    648.             result:{
    649.               elements:[]
    650.             },
    651.             status:0
    652.           };
    653.           for (var i = 0; i < locationTo.length; i++) {
    654.             data.result.elements.push({//将坐标存入
    655.               distance: Utils.getDistance(result.latitude, result.longitude, locationTo[i].lat, locationTo[i].lng),
    656.               duration:0,
    657.               from:{
    658.                 lat: result.latitude,
    659.                 lng:result.longitude
    660.               },
    661.               to:{
    662.                 lat: locationTo[i].lat,
    663.                 lng: locationTo[i].lng
    664.               }
    665.             });            
    666.           }
    667.           var calculateResult = data.result.elements;
    668.           var distanceResult = [];
    669.           for (var i = 0; i < calculateResult.length; i++) {
    670.             distanceResult.push(calculateResult[i].distance);
    671.           }  
    672.           return options.success(data,{
    673.             calculateResult: calculateResult,
    674.             distanceResult: distanceResult
    675.           });
    676.         };
    677.          
    678.         Utils.locationProcess(options, locationsuccess);
    679.       } else {
    680.         var locationsuccess = function (result) {
    681.           requestParam.from = result.latitude + ',' + result.longitude;
    682.           wx.request(Utils.buildWxRequestConfig(options, {
    683.             url: URL_DISTANCE,
    684.             data: requestParam
    685.           },'calculateDistance'));
    686.         };
    687.         Utils.locationProcess(options, locationsuccess);
    688.       }      
    689.   }
    690. };
    691. module.exports = QQMapWX;
    3.在需要获取位置信息页面引入使用
    3.1引入文件sdk
    import QQMapWX from "@/utils/tenxun/qqmap-wx-jssdk.js"
    3.2 获取位置信息方法-复制要填写key,里面有各种信息,根据需求看打印信息
    1. // 获取位置信息
    2. async getLocationInfo() {
    3. //获取位置信息
    4. return new Promise((resolve) => {
    5. //位置信息默认数据
    6. let location = {
    7. longitude: 0,
    8. latitude: 0,
    9. province: "",
    10. city: "",
    11. area: "",
    12. street: "",
    13. address: "",
    14. };
    15. // 获取经纬度(gcjo2)腾讯地图可直接使用
    16. uni.getLocation({
    17. type: "gcj02",
    18. success(res) {
    19. location.longitude = res.longitude;
    20. location.latitude = res.latitude;
    21. // 腾讯地图Api
    22. const qqmapsdk = new QQMapWX({
    23. key: '' //这里填写自己申请的key
    24. });
    25. // 使用腾讯地图api
    26. qqmapsdk.reverseGeocoder({
    27. location,
    28. success(response) {
    29. let info = response.result;
    30. // 注意查看打印信息
    31. console.log('获取位置信息',info);
    32. location.province = info.address_component.province;
    33. location.city = info.address_component.city;
    34. location.area = info.address_component.district;
    35. location.street = info.address_component.street;
    36. location.address = info.address;
    37. // 详细地址
    38. location.recommend = info.formatted_addresses.recommend
    39. location.rough = info.formatted_addresses.rough
    40. // 我使用这里面地址
    41. location.standard_address = info.formatted_addresses
    42. .standard_address
    43. resolve(location);
    44. },
    45. });
    46. },
    47. fail(err) {
    48. console.log(err)
    49. },
    50. });
    51. });
    52. },
    3.3使用该方法获取地址
    1. // 获取当前地址
    2. const location = await this.getLocationInfo();
    3. console.log('获取地址', location);
    4.测试效果
    • 使用微信开发者工具测试时会出现定位不准-正常,会弹起授权框询问用户是否愿意获取位置信息

    • 使用真机测试,或者体验版测试位置就准了,根据自己需求看打印获取信息,自己组装


    总结:

    经过这一趟流程下来相信你也对 uni-app 使用uni.getLocation获取经纬度配合腾讯地图api获取当前地址 有了初步的深刻印象,但在实际开发中我 们遇到的情况肯定是不一样的,所以我们要理解它的原理,万变不离其宗。加油,打工人!

    有什么不足的地方请大家指出谢谢 -- 風过无痕

  • 相关阅读:
    照片后期处理软件DxO FilmPack 6 mac中文说明
    HTML5期末大作业:游戏网站设计与实现——基于bootstrap响应式游戏资讯网站制作HTML+CSS+JavaScript...
    数据库并发问题及四种隔离级别
    虚拟内存分配
    Mysql DateTime 问题
    优化 cesium 界面广告牌(billboard)数据量大于 10w +时,地图加载缓慢、卡顿、加载完成后浏览器严重卡顿甚至崩溃问题
    前端开发学习之【Vue】-上
    c语言-数据结构-栈和队列的实现和解析
    期刊级别应该是怎样划分的呢?
    开发手机软件需要学什么内容才可以呢
  • 原文地址:https://blog.csdn.net/weixin_53579656/article/details/134563230