uniapp中实现微信H5定位、解决跨域问题

uniapp中实现微信H5定位

跨域问题:

移动端h5中直接使用WebServiceAPI可能会有跨域问题,前端最简单的解决方法就是jsonp,
但uniapp中再使用jQuery的ajax就不太友好了,经过查阅资料,大致有两种方法
1、配置uni-app 中 manifest.json->h5->devServer

"h5": {
        "devServer": {
            "port": 8080,
            "disableHostCheck": true,
            "proxy": {
                "/api": {
                    "target": "http://xxx",
                    "changeOrigin": true,
                    "secure": false
                     // 会把程序中/api开头的路径替换成:http://test.com:xxxx/api
                    "pathRewrite": {
                  	"^/api": "/" // 设置/api路径重定向
                	}
                }
            }
        }
    }

2、使用vue-jsonp

安装依赖

npm install vue-jsonp --save

全局引入

//main.js中添加

import VueJsonp from 'vue-jsonp'

Vue.use(VueJsonp)

使用

this.$jsonp(url,data).then(res=>{
			console.log(res)	
})

获取定位

1、首先uni.getLocation获取定位,获取经纬度

uni.getLocation({
    type: 'wgs84',//默认为 wgs84 返回 gps 坐标,gcj02 返回国测局坐标
    success: function (res) {
        console.log('当前位置的经度:' + res.longitude);
        console.log('当前位置的纬度:' + res.latitude);
        
    }
})

2、逆地址解析

uni.getLocation({
    type: 'wgs84',//默认为 wgs84 返回 gps 坐标,gcj02 返回国测局坐标
    success: function (res) {
        console.log('当前位置的经度:' + res.longitude);
        console.log('当前位置的纬度:' + res.latitude);
        let url='https://apis.map.qq.com/ws/geocoder/v1/'
        let data={
					 location:res.latitude+','+res.longitude,
					 key: '腾讯地图的key',
					 output:'jsonp',
					 callback:'jsonp'
				}
				that.$jsonp(url,data).then(res=>{
					if(res.status==0){
						console.log(res.result.ad_info.adcode)
						
					}else{
						console.log(res)
					}
				})
    }
})

或者直接使用ip定位

		let url='https://apis.map.qq.com/ws/location/v1/ip'
		let data={
			
			 key: '腾讯地图的key',
			 output:'jsonp',
			 callback:'jsonp'
		}
		that.$jsonp(url,data).then(res=>{
			if(res.status==0){
				console.log(res.result.ad_info.adcode)
			}else{
				console.log(res)
			}
			
			
		})

如果在多处使用可以添加到全局,并处理异步请求

Vue.prototype.getLocation= function() {

	let that=this
	return new Promise((resolve, reject) => {
				let url='https://apis.map.qq.com/ws/location/v1/ip'
				let data={
					 key: '腾讯地图的key',
					 output:'jsonp',
					 callback:'jsonp'
				}
				that.$jsonp(url,data).then(res=>{
					if(res.status==0){
						console.log(res.result.ad_info.adcode)
						resolve(res.result.ad_info.adcode)
					}else{
						reject(0)
					}
				})
		});
	}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值