vue公众号打开腾讯地图并计算距离

第一步 引入腾讯cdn

1、在index.html 中引入

  <script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=存放自己的key"></script>

第二步、在需要的页面引入jssdk

安装

npm install weixin-js-sdk --save

引入

import wx from "weixin-js-sdk";
import Vue from "vue";
Vue.use(wx);

第三步、通过config接口注入权限验证配置

   // 微信页面初始化配置接口
    getWxConfigHome() {
      api.appWxConfig(this.wechartParams).then(json => {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId: json.appId, // 必填,公众号的唯一标识
          timestamp: json.timestamp, // 必填,生成签名的时间戳
          nonceStr: json.nonceStr, // 必填,生成签名的随机串
          signature: json.signature, // 必填,签名
          jsApiList: [
            "getLocation",
            "chooseWXPay",
            "updateAppMessageShareData",
            "openLocation"
          ] // 必填,需要使用的JS接口列表    微信支付   禁止分享
        });
        wx.ready(() => {
        // 成功 获取当前地址
          this.wxGetLocation();
        });
        wx.error(function(res) {
          // alert(JSON.stringify(res));
        });
      });
    }
    wxGetLocation() {
      wx.getLocation({
        type: "wgs84", // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
        success: res => {
        	// 转换成腾讯相关的经纬度
          this.startLocation = new qq.maps.LatLng(res.latitude, res.longitude); 
          // 创建一个地址解析器 
          this.geoCoder = new qq.maps.Geocoder();
          // 逆地址解析
          this.geoCoder.getAddress(this.startLocation);
          // 地址解析失败的回调
          this.geoCoder.setError(() => {
            Toast("位置获取失败,请检查你的手机是否开启定位");
          });
          // 地址解析成功的回调
          this.geoCoder.setComplete(result => {
            const cityName = result.detail.addressComponents.city;
            const provinceName = result.detail.addressComponents.province;
            const areaName = result.detail.addressComponents.district;
            this.location =
              result.detail.addressComponents.province +
              result.detail.addressComponents.city +
              result.detail.addressComponents.district +
              result.detail.addressComponents.street;
          });
        },
        fail: () => {
          Toast("定位失败,请检查你的手机是否开启定位");
        },
        cancel: function(res) {
          alert("用户拒绝授权获取地理位置");
        }
      });
    },

打开地图

html

<div style="color: rgba(189, 189, 189, 100);font-size:14px" @click="openMap(item1)">
	{{ item1.address }} 
</div>

js

    openMap(item) {
      console.log("1");
      wx.openLocation({
        latitude: item.latitude, // 纬度,浮点数,范围为90 ~ -90
        longitude: item.longitude, // 经度,浮点数,范围为180 ~ -180。
        name: "", // 位置名
        address: item.address, // 地址详情说明
        scale: 15, // 地图缩放级别,整形值,范围从1~28。默认为最大
        infoUrl: "" // 在查看位置界面底部显示的超链接,可点击跳转
      });
    },

计算距离

//计算距离
// lcoation 本地地址    lat2 目标所在维度    lng2 目标所在经度
export function distance(location,lat2,lng2){
  if(!location.lat){
    return false
  }
  let lat1=location.lat,
    lng1=location.lon;
  let radLat1 =lat1 * Math.PI / 180.0
  let radLat2 =lat2 * Math.PI / 180.0
  let a = radLat1 - radLat2;
  let  b =lng1 * Math.PI / 180.0-lng2 * Math.PI / 180.0
  let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
  s = s *6378.137 ;// EARTH_RADIUS;
  s = Math.round(s * 100) / 100; //输出为公里
  return s
}

全部代码

<template>
  <div class="bg">
    <van-tabs v-model="active" class="box-bg" @click="btnClick">
      <van-tab
        v-for="(item, index) in tabList"
        :title="item"
        :key="index"
        class="item-bg"
      >
        <div v-for="(item1, index1) in List" :key="index1" class="item">
          <div class="item-div">
            <div>{{ item1.merchantName }}</div>
            <div style="color: rgba(189, 189, 189, 100);">
              {{ getDistance(item1.latitude, item1.longitude) }}
            </div>
          </div>
          <div
            style="color: rgba(189, 189, 189, 100);font-size:14px"
            @click="openMap(item1)"
          >
            {{ item1.address }}
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import api from "@/api";
import wx from "weixin-js-sdk";
import Vue from "vue";
Vue.use(wx);

export default {
  data() {
    return {
      active: 0, // 活动
      merchantId: "",
      param: {
        merchantId: "",
        token: api.getToken(),
        limit: 100,
        page: 0
      },
      tabList: [
        "品牌咖啡",
        "大邑商户",
        "海底捞火锅",
        "我的商户",
        "壹卡惠",
        "舞东风超市",
        "星巴克"
      ],
      List: []
    };
  },
  computed: {},
  watch: {},
  mounted() {
    document.title = "可用门店";
    this.getWxConfigHome();
    this.param.merchantId = "530912";
    this.getList();
  },
  methods: {
    openMap(item) {
      console.log("1");
      wx.openLocation({
        latitude: item.latitude, // 纬度,浮点数,范围为90 ~ -90
        longitude: item.longitude, // 经度,浮点数,范围为180 ~ -180。
        name: "", // 位置名
        address: item.address, // 地址详情说明
        scale: 15, // 地图缩放级别,整形值,范围从1~28。默认为最大
        infoUrl: "" // 在查看位置界面底部显示的超链接,可点击跳转
      });
    },
    // 获得列表
    getList() {
      api
        .SotreList(this.param)
        .then(res => {
          if (res.status === 200) {
            this.List = res.data;
            console.log(this.List, "数据");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 切换标签页
    btnClick(index) {
      console.log(index, "来了");
      if (index === 0) {
        this.param.merchantId = "530912";
        this.getList();
      } else if (index === 1) {
        this.param.merchantId = "528210";
        this.getList();
      } else if (index === 2) {
        this.param.merchantId = "504618";
        this.getList();
      } else if (index === 3) {
        this.param.merchantId = "407084";
        this.getList();
      } else if (index === 4) {
        this.param.merchantId = "1031";
        this.getList();
      } else if (index === 5) {
        this.param.merchantId = "264411";
        this.getList();
      } else if (index === 6) {
        this.param.merchantId = "382028";
        this.getList();
      }
    },
    wxGetLocation() {
      wx.getLocation({
        type: "wgs84", // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
        success: res => {
          const startLocation = new qq.maps.LatLng(res.latitude, res.longitude);
          const geoCoder = new qq.maps.Geocoder();
          geoCoder.getAddress(startLocation);
          geoCoder.setError(() => {
            Toast("位置获取失败,请检查你的手机是否开启定位");
          });
          geoCoder.setComplete(result => {
            console.log('定位成功')
          });
        },
        fail: () => {
          Toast("定位失败,请检查你的手机是否开启定位");
        },
        cancel: function(res) {
          alert("用户拒绝授权获取地理位置");
        }
      });
    },
    // 微信页面初始化配置接口
    getWxConfigHome() {
      api.appWxConfig(this.wechartParams).then(json => {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId: json.appId, // 必填,公众号的唯一标识
          timestamp: json.timestamp, // 必填,生成签名的时间戳
          nonceStr: json.nonceStr, // 必填,生成签名的随机串
          signature: json.signature, // 必填,签名
          jsApiList: [
            "getLocation",
            "chooseWXPay",
            "updateAppMessageShareData",
            "openLocation"
          ] // 必填,需要使用的JS接口列表    微信支付   禁止分享
        });
        wx.ready(() => {
          this.wxGetLocation();
        });
        wx.error(function(res) {
          // alert(JSON.stringify(res));
        });
      });
    }
  }
};
</script>

<style lang='scss' scoped>
.bg {
  width: 100vw;
  height: 100vh;
  background: #f7f7f7;
}
.box-bg {
  background: #f7f7f7;
}
.item-bg {
  background: white;
  margin-top: 10px;
  padding: 0 20px;
}
.item {
  font-family: PingFangSC-regular;
  padding: 10px 0;
  border-bottom: 1px solid rgba(213, 213, 213, 100);
  color: rgba(0, 0, 0, 1);
  font-size: 14px;
}
.item-div {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值