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)
}
})
});
}