自己用

116 阅读2分钟
export default {
    //判断是否在(ios/安卓端)
    isIosAndr() {
      let userAgent = navigator.userAgent.toLowerCase();//获取UA信息
      if (userAgent.indexOf("isapp") != -1) {//判断ua中是否含有和app端约定好的标识
        return true
      } else {
        return false
      }
    },
    //判断是否在安卓端(没有app端约定好的标识)
    isAndroid() {
    
      let type = navigator.userAgent.toLowerCase()
      if (/(android)/i.test(type)) {
        return true;
      } else {
        return false
      }
    
    },
    //判断是否在ios(没有app端约定好的标识)
    isIos() {
      let type = navigator.userAgent.toLowerCase()
      if (/(iphone|ipad|ipod|ios)/i.test(type)) {
        return 1;
      } else {
        return false
      }
    
    },
    // 判断环境是否在微信小程序里
    isMiniProgram() {
      var ua = navigator.userAgent.toLowerCase();
      var envType = 3;
      if (ua.match(/MicroMessenger/i) == 'micromessenger') { //微信环境
        wx.miniProgram.getEnv(function (res) {
          if (res.miniprogram) { // 小程序环境下逻辑
            envType = 1
          } else { //非小程序环境下逻辑
            envType = 2
          }
        })
      } else { //非微信环境逻辑
        envType = 3
      }
      return envType
    },
    ////html剔除富文本标签,留下纯文本
    getSimpleText(html) {
      var re1 = new RegExp("<.+?>", "g");//匹配html标签的正则表达式,"g"是搜索匹配多个符合的内容
      var msg = html.replace(re1, '');//执行替换成空字符
      return msg;
    },
    // 将百度地图经纬度转换为腾讯/高德地图经纬度
    bMapTransQQMap(lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta);
      let lats = z * Math.sin(theta);
    
      return {
        longitude: lngs,
        latitude: lats
      }
    },
    //富文本图片点击事件
    imageEnlargement(e) {
      console.log(e);
      if (e.target.nodeName == "IMG") {
        //判断点击富文本内容为img图片
        let index = this.imgPreList.findIndex((item) => {
          return item == e.target.currentSrc;
        });
        this.index = index;
        if (isBaiDuClient()) {
          this.imgShow = true;
        } else if (isIosAndr()) {
          //app
          let host = "yunjj://";
          let content = "";
          content = `{"key":"viewPicture","params":{"currentIndex":${index},"imgList":${JSON.stringify(
            this.imgPreList
          )}},"callback":" ",}`;
          content = Base64.encode(content);
          console.log("Url:" + Base64.decode(content));
          window.location.replace(host + content);
        } else {
          //微信环境
          this.imgShow = true;
        }
        // ImagePreview({
        //   images: this.imgPreList, //获取当前图片src
        //   showIndex: true,
        //   startPosition: index,
        //   loop: false,
        // });
      } else {
        console.log("点击内容不为img");
      }
    },
    //获取url上的键值对的值
    getQueryVariableK(variable, url) {
      // var query = window.location.search.substring(1);
      var vars = url.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
      }
      return (false);
    },
    //初始化微信jssdk
     /**
      * 
      * @param {*} that 
      * @param {*} title 分享标题
      * @param {*} link 分享链接
      * @param {*} imgUrl 分享icon
      * @param {*} desc 分享描述
      */
     initWeChatShare(that, title = '无忧找房', link = location.href, imgUrl = 'https://xxxxx/public/pro/banjia-logo.png', desc = location.href, callback) {
       if (isWxClient()) {
         //因为微信最近调整了规则,你必须在公众号菜单中打开,才能正常分享
         let url = "";
         if (process.env.NODE_ENV == "production") {
           url =
             window.location.origin +
             "/yjj_1_4/common/getJsApi?url=" +
             encodeURIComponent(window.location.href);
         } else {
           url =
             "/getJsApi?url=" +
             encodeURIComponent(window.location.href);
         }
         that.$http.get(url).then((result) => {
           if (result) {
             wx.config({
               debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
               appId: result.appId, // 必填,公众号的唯一标识
               timestamp: result.timestamp, // 必填,生成签名的时间戳
               nonceStr: result.noncestr, // 必填,生成签名的随机串
               signature: result.signature, // 必填,签名,见附录1
               jsApiList: [
                 "updateAppMessageShareData",
                 "updateTimelineShareData",
                 "checkJsApi",
               ], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
               openTagList: ['wx-open-launch-weapp'], // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
               success: function (res) {
                 console.log("config 成功", res);
                 callback()
               },
               fail: function (res) {
                 alert("微信jsdk授权失败", res.errMsg);
                 console.log("微信jsdk授权 fail", res);
               }
             });
             wx.ready(function () {
               wx.checkJsApi({
                 jsApiList: [
                   "updateAppMessageShareData",
                   "updateTimelineShareData",
                   "checkJsApi",
                 ]
               });
               callback()
     
               console.log("ready====");
               wx.updateAppMessageShareData({
                 title: title, // 分享标题
                 desc: desc, //描述
                 link: link, // 分享链接
                 imgUrl: imgUrl, // 分享图标
                 success: function () {
                   console.log("设置成功");
                 }
               });
               wx.updateTimelineShareData({
                 title: title, // 分享标题
                 link: link, // 分享链接
                 imgUrl: imgUrl, // 分享图标
                 success: function () {
                   console.log("分享成功");
                 },
                 cancel: function () {
                   console.log("取消了分享");
                 }
               });
             });
           }
         });
         wx.error(function (res) {
           // alert("出错了",res)
         });
       }
     },
     // 百度地图召唤
     wakeBaidu(urlObject) {
       if (localStorage.getItem("latitude") && localStorage.getItem("longitude")) {
         var latCurrent = localStorage.getItem("latitude"); //获取到的纬度
         var lngCurrent = localStorage.getItem("longitude") //获取到的经度
         if (latCurrent && lngCurrent) {
           var scheme = '';
     
           // urlObject 是我这边地址栏查询参数对象
           var queryStr = '?origin=name:我的位置|latlng:' + latCurrent + ',' + lngCurrent + '&destination=' + urlObject.lat + ',' + urlObject.lng + '&region=' + urlObject.city + '&coord_type=bd09ll&mode=driving';
     
           var u = navigator.userAgent, app = navigator.appVersion;
           if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
             // ios 端
             scheme = 'baidumap://map/direction' + queryStr;
           } else {
             // android 端
             scheme = 'bdapp://map/direction' + queryStr;
           }
     
           // 主要实现代码
           window.location.href = scheme;
     
           var startTime = Date.now();
           var count = 0;
           var endTime = 0;
     
           var t = setInterval(function () {
             count += 1;
             endTime = Date.now() - startTime;
             if (endTime > 800) {
               clearInterval(t);
             }
             if (count < 30) return;
             if (!(document.hidden || document.webkitHidden)) {
               window.location.href = 'http://api.map.baidu.com/direction' + queryStr + '&output=html';
             }
           }, 20);
     
           window.onblur = function () {
             clearInterval(t);
           };
         }
         return;
       }
       var geolocation = new BMap.Geolocation();
       geolocation.getCurrentPosition(function (result) {
         if (this.getStatus() == BMAP_STATUS_SUCCESS) {
           var latCurrent = result.point.lat; //获取到的纬度
           var lngCurrent = result.point.lng; //获取到的经度
           if (latCurrent && lngCurrent) {
             var scheme = '';
     
             // urlObject 是我这边地址栏查询参数对象
             var queryStr = '?origin=name:我的位置|latlng:' + latCurrent + ',' + lngCurrent + '&destination=' + urlObject.lat + ',' + urlObject.lng + '&region=' + urlObject.city + '&coord_type=bd09ll&mode=driving';
     
             var u = navigator.userAgent, app = navigator.appVersion;
             if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
               // ios 端
               scheme = 'baidumap://map/direction' + queryStr;
             } else {
               // android 端
               scheme = 'bdapp://map/direction' + queryStr;
             }
     
             // 主要实现代码
             window.location.href = scheme;
     
             var startTime = Date.now();
             var count = 0;
             var endTime = 0;
     
             var t = setInterval(function () {
               count += 1;
               endTime = Date.now() - startTime;
               if (endTime > 800) {
                 clearInterval(t);
               }
               if (count < 30) return;
               if (!(document.hidden || document.webkitHidden)) {
                 window.location.href = 'http://api.map.baidu.com/direction' + queryStr + '&output=html';
               }
             }, 20);
     
             window.onblur = function () {
               clearInterval(t);
             };
           } else {
             alert('获取不到定位,请检查手机定位设置');
           }
         }
       });
     },
     //使用
    // let params = {
    //    lat: item.latitude,
    //    lng: item.longitude,
    //    city: item.address,
    //  }
    //  wakeBaidu(params)
    //节流函数
    throttle(fn, wait) {
      var timer = null;
      return function () {
        var context = this;
        var args = arguments;
        if (!timer) {
          timer = setTimeout(function () {
            fn.apply(context, args);
            timer = null;
          }, wait)
        }
      }
    },
    //数字分隔,
    toThousands(num) {
       var num = (num || 0).toString(), result = '';
       while (num.length > 3) {
           result = ',' + num.slice(-3) + result;
           num = num.slice(0, num.length - 3);
       }
       if (num) { result = num + result; }
       return result;
   },
   //随机颜色
   const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
   
   
}
//打开地图
		openMap() {
			// #ifdef H5
			// 在h5内
			if (isWeiXin()) {
				//在微信浏览器内
				//打开指定位置
				this.wxApi.config({
					debug: false,
					appId: data.appId,
					timestamp: data.timestamp,
					nonceStr: data.nonceStr,
					signature: data.signature,
					jsApiList: ['checkJsApi', 'openLocation'],
					success(res) {
						//   Toast(res);
					},
				})
				this.wxApi.ready(() => {
					this.wxApi.checkJsApi({
						jsApiList: ['openLocation'],
						success: rest => {
							// Toast("ready*****",rest);
							//打开指定位置
							this.wxApi.openLocation({
								latitude: Number(this.currentStore.latitude), // 纬度,浮点数,范围为90 ~ -90
								longitude: Number(this.currentStore.longitude), // 经度,浮点数,范围为180 ~ -180。
								name: this.currentStore.storeName, // 位置名
								address: this.currentStore.address, // 地址详情说明
								scale: 18, // 地图缩放级别,整型值,范围从1~28。默认为最大
								infoUrl: '', // 在查看位置界面底部显示的超链接,可点击跳转
							})
						},
					})
				})
			} else {
				let url = `https://apis.map.qq.com/tools/routeplan/eword=${this.currentStore.address}&epointx=${Number(
					this.currentStore.latitude,
				)}&epointy=${Number(this.currentStore.longitude)}?referer=${
					this.currentStore.storeName
				}&key=KFHBZ-BB4RD-4D64U-HLNQG-MQYQQ-WBFXP`
				window.location.href = url
			}

			// #endif
			// #ifdef MP-WEIXIN
			// 在微信小程序内
			uni.openLocation({
				latitude: Number(this.currentStore.latitude),
				longitude: Number(this.currentStore.longitude),
				name: this.currentStore.storeName,
				address: this.currentStore.address,
			})
			// #endif
		},