微信小程序之封装获取位置距离的方法

效果图:

在这里插入图片描述

1. mine.js代码

/**
 * $convertAddressListToLication   将地址名称集合 转换为  地址坐标集合
 * $getDistanceOneToMany          计算地址之间的距离
 * $getLocation               获取当前位置的坐标
 */
 
import {
  $convertAddressListToLication,
  $getDistanceOneToMany,
  $getLocation
} from '../../utils/location.js'
Page({
	  data: {
    shoplist: [{
        id: 1,
        address: '深圳市久荣物流有限公司',
        name: '万达店',
        distance: 0,
      },
      {
        id: 2,
        address: '内蒙古乌兰察布市集宁区恩和路',
        name: '包子店',
        distance: 0,
      },
      {
        id: 3,
        address: '内蒙古乌兰察布市集宁区光辉小区',
        name: '江林店',
        distance: 0,
      }
    ],
  },

	async getDistance() {
    //获取当前位置坐标集合
    let myLocation = await $getLocation()
    //把shoplist集合转换为shoplist集合中的address字段的集合并且命名为addressList
    let addressList = this.data.shoplist.map(r => r.address)
    //将地址的集合传入调用$convertAddressListToLication这个方法得到地址坐标的集合toLocationList
    let toLocationList = await $convertAddressListToLication(addressList)
    //将我的位置坐标集合myLocation和得到的shoplist的地址转换后的地址坐标集合传入$getDistanceOneToMany得到距离的集合distanceList
    let distanceList =  await $getDistanceOneToMany(myLocation , toLocationList)

    //遍历shoplist给其中的distance依次赋值
    this.data.shoplist.forEach((r , i) => {
      r.distance = distanceList[i]
    });
    this.setData({
      shoplist:this.data.shoplist
    })
  },
})

2.location.js


/** 
 * $parseVars2Str将集合中的元素用逗号拼接成字符串
 * MAP_KEY   mapkey的id
 * $get  request中的get请求的封装函数
 */


import {
  $parseVars2Str
} from '../utils/util.js'

import {
  MAP_KEY
} from '../config/index.js'

import {
  $get
} from '../utils/requestbasic.js'


//获取当前位置经纬度
export function $getLocation() {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
      altitude: 'altitude',
      complete: (res) => {},
      fail: (res) => {},
      highAccuracyExpireTime: 0,
      isHighAccuracy: true,
      success: ({
        //longitude:lng, 给longitude变量取别名为lng
        longitude: lng,
        latitude: lat
      }) => {
        resolve({
          lat,
          lng
        })
      },
    })
  })
}

/**
 *   将list集合中的地址列表同时转换成坐标列表
 *   addressList为地名的列表集合
 *   prolist:空列表用于放置循环后的每一个被转换的坐标集合
 *   $convertAdressToLocation(r)  循环将每一个地名转换为坐标
 *   prolist.push(pro)   放入prolist
 *   let res = await Promise.all(prolist)   将prolist中的所有pro统一发起请求 同时转换为地址坐标
 */
export async function $convertAddressListToLication(addressList) {
  let prolist = []
  addressList.forEach(r => {
    let pro = $convertAdressToLocation(r)
    prolist.push(pro)
    // console.log(JSON.stringify(this.data.shoplist))
  });
  // 统一发起请求
  let res = await Promise.all(prolist)
  return res;
}


/**
 * 
 * 
 * 获取一对多的距离
 * fromLocation{lat , lng}
 * fromLocation   起始位置的坐标集合
 * toLocationList:[{lat , lng},{lat , lng},{lat , lng}]    接收$convertAddressListToLication这个方法返回的位置坐标的集合
 * let to = (toLocationList.map(r => {return $parseVars2Str(r.lat, r.lng)}).join(";"));   将拿到的toLocationList集合转换为[r.lat, r.lng ; r.lat, r.lng ; r.lat, r.lng]   这样的集合
 * 
 * 
 */
export async function $getDistanceOneToMany(fromLocation , toLocationList) {
  //组装数组
  let to = (toLocationList.map(r => {
    return $parseVars2Str(r.lat, r.lng)
  }).join(";"));

  //请求调用$get()方法获取距离
  let {result} = await $get('https://apis.map.qq.com/ws/distance/v1/', {
    mdoe: 'driving',
    from: $parseVars2Str(fromLocation.lat, fromLocation.lng),
    to,
    key: MAP_KEY,
  })
  // console.log(JSON.stringify(distance.result.elements))
  //转换为距离集合
  let distanceList = result.elements.map(r => r.distance)
  return distanceList
}

3.util.js

//用逗号拼接
export function $parseVars2Str(...args) {
  // return Array.prototype.join.call(arguments , ',');
  return args.join(",")
}

4.requestbasic.js

//wx.request工具类

/*
  参数为三个参数:_this传参为this指针   ,   url为接口地址   ,   list为page页面data中定义的集合的名称,形式为字符串

  函数为getListsByGet         getListsByPost   

  引入方法:
        import {
          $getListsByGet
        } from '../../utils/ajax.js';
        
        存在问题接口中的集合名称需要在此工具文档中修改
  
*/

import {
  BasicUrl
} from '../config/index.js';

//封装wx.request
function $res(url, method , data) {

  wx.showLoading({
    title: '加载中...',
  })

  return new Promise((resolve, reject) => {
    wx.request({
      url: url.startsWith("http") ? url : BasicUrl + url,
      method,
      data,
      success: (res => {
        resolve(res.data)
      }),
      fail(e) {
        reject(e)
      },
      complete(){
        wx.hideLoading()
      }
    })
  })
}

//封装的get请求方式的wx.request
export function $get(url , data) {
  return $res(url, 'Get' , data)
  // pro.then(res => {
  //   console.log(res)
  // })
}

//封装的post请求方式的wx.request
export function $post(url , data) {
  return $request(url, 'POST' , data)
  let pro = $request(url, 'POST')
  pro.then(res => {
    console.log(res)
  })
}

5.config/index.js

export const MAP_KEY = 'CQBBZ-N5KWU-25AV6-2NODO-V2XQ2-MMFOX'

6.mine.wxml


<view wx:for="{{shoplist}}" class="shoplist">

  {{item.name}}

  <view class="address">
    {{item.address}}
    ---距离您{{item.distance}}米
  </view>
  
  <button class="btn" data-address="{{item.address}}" bindtap="change">定位</button>
</view>

<map latitude="{{lat}}" longitude="{{lng}}"
style="width:100vw;height:400rpx"
scale="14"  
markers="{{markers}}"

></map>

mine.wxss


.shoplist{
  padding: 30rpx;
}

.address{
  font-size: 25rpx;
  color: #999;
  padding: 20rpx;
}

.btn{
  width: 50%;
  size: 10rpx;
}
发布了20 篇原创文章 · 获赞 12 · 访问量 7746

猜你喜欢

转载自blog.csdn.net/weixin_44735933/article/details/105566070