使用 wxsdk 或 浏览器 定位

参考 文档: 

关于微信SDK的一些理解和实践 - 掘金

// 这种方式引入 wxsdk,uniapp中 wx. 被占用 

import jWeixin from 'weixin-js-sdk'


 

import { jsonp } from 'vue-jsonp'

const ipUrl = 'https://restapi.amap.com/v3/ip'

import http from '@/util/https.js'

// 判断是否微信环境

const isWx = () => {

    let ua = navigator.userAgent.toLowerCase();

    return /micromessenger/.test(ua)

}

// 微信 sdk 注册  添加异常捕获

export async function initWxSDK(callback, errorCallback) {

    // 非微信环境直接return;

    if (!isWx()) {

        return;

    }

    // jWeixin.config({

    //     debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

    //     appId: '', // 必填,公众号的唯一标识

    //     timestamp: '', // 必填,生成签名的时间戳

    //     nonceStr: '', // 必填,生成签名的随机串

    //     signature: '',// 必填,签名

    //     jsApiList: ['getLocation', 'openLocation'] // 必填,需要使用的JS接口列表

    // })

    let paramUrl = window.location.href.split("#")[0];

    let res = await http('/base/app/wx/sign/getQwConfig', {url: paramUrl} , 'post')

    let {appId, timestamp, signature, nonceStr} = (res?.data?.data || {})

    jWeixin.config({

        beta: true,     // 必须这么写,否则wx.invoke调用形式的 jsapi 会有问题

        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

        appId, // 必填,企业微信corpId

        timestamp,// 必填,生成签名的时间戳

        nonceStr, // 必填,生成签名的随机串

        signature,// 必填,签名

        jsApiList: ['getLocation', 'openLocation'] // 必填,需要使用的JS接口列表

    })

    jWeixin.ready(function () {

        uni.setStorageSync('useWXSDK', true)

        callback && callback();

        // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。

    });

    jWeixin.error(function (err) {

        errorCallback && errorCallback(err)

        uni.removeStorageSync('useWXSDK')

    })

}

//在需要定位页面调用  

export function getlocation_WX(option) {

    let { type = 'gcj02', success, fail } = option;

    if (!isWx()) {

        return;

    };

    initWxSDK(() => {

        jWeixin.getLocation({

            type, // 默认为gcj02的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'wgs84'

            success: function (res) {

                let latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90

                let longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。

                let speed = res.speed; // 速度,以米/每秒计

                let accuracy = res.accuracy; // 位置精度

                let position = {

                    longitude, latitude

                }

               

                alert('调用微信sdk成功')

                success && success(position)

            },

            fail: function (err) {

                alert('调用微信sdk失败')

                fail && fail(err)

            }

        })

    },

    (err) => {

        let str = '';

        try{

            for(let i in err) {

                str += i + ' : ' + err[i] + ';'

            }

        }catch(error) {

        }finally{

            fail && fail(str)

        }

     

       

    }

    )

}


 

//  H5 定位

export const getLoaction_H5 = (option) => {

    let { success, fail } = option;

    function onSucess(res) {

        let coords = res.coords

        let position = {

            longitude: coords.longitude,

            latitude: coords.latitude

        }

        success && success(position)

    }

    function onError(res) {

        getLatByIP_amap(option)

        fail && fail(res)

    }

    if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(onSucess, onError, {

            enableHighAccuracy: true,

            timeout: 3000,

            maximumAge: 0,

        });

    } else {

        console.log('不支持H5定位, 改用高德 ip 定位');

        getLatByIP_amap(option)

    }

};


 

// 高德ip定位

export const getLatByIP_amap = (option) => {

    let { success, fail } = option;

    jsonp(ipUrl, {

        key: ‘’,

        output: 'json'

    }).then(res => {

        if (res.status == 1) {

        // 手机上使用, 一般情况下浏览器定位可以拿到值,不会走到ip定位上

        // 这块处理比较粗糙, 直接取范围的中心点

        //  可改为 使用逆地址解析来获取 坐标信息

            let list = res.rectangle.replace(';', ',').split(',')

            let position = {

                longitude: (+list[0] + +list[2]) / 2,

                latitude: (+list[1] + +list[3]) / 2,

            }

            success && success(position)

        } else {

            fail && fail(res);

        }

    }).catch(err => {

        fail && fail(err)

    })

}



 

// wx 打开第三方地图app

// 这块 属用户手动触发,可直接调用 openLocation,方法不需要nitWxSDK回调

// 因原项目中 其他浏览器跳转 已有,这块并没有封装

export const openMapApp = (option) => {

    // 这样封装是为了尽量不动原代码逻辑

    if(!isWx()) {

        return true;

    }

    let {lat, lng, customerName} = option;

    initWxSDK(() => {

        jWeixin.openLocation({

            latitude: lat,

            longitude: lng,

            name: customerName,

            address: ""

        })

    })

}


 

  • 17
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值