uniapp使用腾讯地图实现商家定位

一丶申请腾讯位置服务开发者密钥

官网教程:微信小程序JavaScript SDK | 腾讯位置服务

点击申请密钥
在这里插入图片描述
创建应用,然后添加Key
在这里插入图片描述
添加key,并且勾选WebServiceApi
在这里插入图片描述

二丶下载微信小程序JavaScriptSDK

下载链接: https://mapapi.qq.com/web/miniprogram/JSSDK/qqmap-wx-jssdk1.2.zip
在这里插入图片描述

三丶安全域名设置

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

四、代码编写

  1. 在项目中创建utils目录将下载好JavaScriptSDK放入其中,并在uniapp中导入。
    在这里插入图片描述
 import QQMapWX from '@/utils/qqmap-wx-jssdk.js'
  const qqmapsdk = new QQMapWX({
    //填写你申请的key
    key: '****-****-****-****-****-****'
  })

2. 编写代码

这里在使用前有两个注意事项,很重要,否则调用不成功

  1. 在调用方法之前,需要在控制台 -> 配额管理 -> 账号额度 对指定接口进行手动配额分配(免费的),否则每天就只会有一次调用接口的机会。
    在这里插入图片描述

  2. 在计算步行距离时如果调用这个方法qqmapsdk.calculateDistance是不生效的,
    官方已经不再维护,需要自己手动调用地址https://apis.map.qq.com/ws/distance/v1/matrix
    同理该接口也需要手动进行配额分配。
    在这里插入图片描述

  import QQMapWX from '@/utils/qqmap-wx-jssdk.js'
  const qqmapsdk = new QQMapWX({
    //填写你申请的key
    key: '****-****-****-****-****-****'
  })
export default {
    data() {
      return {
        //商家列表
        markers: JSON.parse(uni.getStorageSync("markers")||'[]'),
        //自身经纬度
        from: {},
        //页码值
        page_index: 1,
        //每页显示多少条数据
        page_size: 10,
        //分页总条数
        total: 100,
      }
    },
    methods: {
      chooseLocation(){
        let that = this
      	uni.chooseLocation({
      		success: (data)=> {
      			that.from.latitude = data.latitude
      			that.from.longitude = data.longitude
            that.getViennaList()
      		},
          fail:(e)=>{
            uni.showToast({
              title: '无法获取当前位置!',
              icon: 'error',
              duration: 1500
            });
          }
      	})
      },
      chooseStore() {
        //获取当前地理位置
        let that = this
        uni.getLocation({
          type: 'gcj02',
          success(res) {
            console.log('---getLocation---', res)
            that.from.latitude = res.latitude
            that.from.longitude = res.longitude
            that.getViennaList()
          },
          fail: (err) => {
            console.log('---errgetLocation---', err)
            uni.showToast({
              title: '无法获取当前位置!',
              icon: 'error',
              duration: 1500
            });
          }
        })
      },
      getViennaList() {
        //获取商家位置
        let that = this
        console.log(that.from)
        qqmapsdk.search({
          //关键字改成所需商家名称
          keyword: "奈雪的茶",
          //自身经纬度对象
          location: that.from,
          //分页(可忽略)
          page_index: that.page_index,
          page_size: that.page_size,
          success: (res) => {
            var mks = []
            for (var i = 0; i < res.data.length; i++) {
              mks.push({ // 获取返回结果,放到mks数组中
                title: res.data[i].title,
                id: res.data[i].id,
                latitude: res.data[i].location.lat,
                longitude: res.data[i].location.lng,
                address: res.data[i].address,
                distance: ''
              })
            }
            that.changeWidth(mks);
          },
          fail: (err) => {
            console.log('--qqmapsdk.search err---', err)
            uni.showToast({
              title: '无法获取商店位置!',
              icon: 'error',
              duration: 1500
            });
          }
        })
      },
      //计算距离
      changeWidth(mks) {
        let _this = this
        let fromAddress = `${_this.from.latitude},${_this.from.longitude}`
        console.log(fromAddress)
        let toAddress = '';
        for (let i = 0; i < mks.length; i++) {
          toAddress += `${mks[i].latitude},${mks[i].longitude}`
          if (i != mks.length - 1) {
            toAddress += ';'
          }
        }
         uni.request({
           url: 'https://apis.map.qq.com/ws/distance/v1/matrix',
           method: 'POST',
           data: {
             mode: 'walking',
             from: fromAddress,
             to: toAddress,
             //填写你申请的key 
             key: 'xxx-xxxx-xxxx-xxxx-xxxx-xxxx'
           },
           success: (res) => {
             console.log(res)
                for (let i = 0; i < res.data.result.rows[0].elements.length; i++) {
                  let hw = res.data.result.rows[0].elements[i].distance
                  if (hw && hw !== -1) {
                    if (hw < 1000) {
                      hw = hw + 'm';
                    } else {
                      hw = (hw / 2 / 500).toFixed(2) + 'km'
                    }
                  } else {
                    hw = "距离太近或请刷新重试"
                  }
                  mks[i].distance = hw
                }
                _this.markers = mks
                console.log(_this.markers)
                uni.setStorageSync("markers",_this.markers)
           }
         }) 
      }
    }

  }
**```
3. 调用方法并展示**

```javascript
<template>
  <view class="container" >
    <view class="row b-b">
    	<text class="tit">请选择地址: </text>
    	<input @click="chooseLocation" class="addressInput "  placeholder="请选择地址进行搜索">
    	</input>
    	<text class="yticon icon-shouhuodizhi"></text>
    </view>
  </view>
</template>  
  1. 小程序增加对chooseLocation、getLocation调用权限
    .在manifest.json中加入如下代码,否则获取地址时会出现权限不足
/* 小程序特有相关 */
      "permission" : {
      		    "scope.userLocation" : {
      		        "desc" : "你的位置信息将用于小程序位置接口的效果展示"
      		    }
      		},
       "requiredPrivateInfos" : [ "chooseLocation", "getLocation" ],

在这里插入图片描述

五、实现效果

在这里插入图片描述
最后简单写了一下样式,展示效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值