1 安裝vue-resource, 因為h5請求會跨域,我們需要安裝這個插件
cnpm install vue-jsonp --save 或 npm install vue-jsonp --save 根據(jù)使用的包管理器來
2 main.js文件中引入vue-resource并通過命令Vue.user()使用該插件
import VueJsonp from ‘vue-jsonp’
Vue.use(VueJsonp)
3 創(chuàng)建一個文件,開始寫功能,我是創(chuàng)建了一個工具文件夾utils放在indedx.js文件夾下
import { jsonp } from 'vue-jsonp';
//app直接獲取地理位置,不需要發(fā)起請求
export function getLocationInfo() { //2. 獲取地理位置
// #ifdef H5
// 適配h5請求跨域問題
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'gcj02',
success: async (res) => {
const latitude = res.latitude.toString();
const longitude = res.longitude.toString();
uni.setStorage({ //將經(jīng)緯度保存到本地
key: 'coordinate',
data: {
'latitude': res.latitude,
'longitude': res.longitude,
},
});
const url = 'https://apis.map.qq.com/ws/geocoder/v1';
//通過經(jīng)緯度換取地址
await jsonp(url, {
key: '4KQBZ-W5N36-CJKSF-EQQN4-2OXTZ-V4F5J',
location: `${latitude},${longitude}`,
output: 'jsonp',
}).then(re => {
// console.log(re, 'Tengx ');
let address = re.result.address_component;
resolve(address);
}).catch(err => {
console.log(err);
reject(err);
});
},
});
});
// #endif
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'gcj02',
success(res) {
let latitude, longitude;
uni.setStorage({ //將經(jīng)緯度保存到本地
key: 'coordinate',
data: {
'latitude': res.latitude,
'longitude': res.longitude
}
});
latitude = res.latitude.toString();
longitude = res.longitude.toString();
uni.request({
header: {
"Content-Type": "application/text"
},
url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' +
longitude + '&key=4KQBZ-W5N36-CJKSF-EQQN4-2OXTZ-V4F5J',
success(re) {
if (re.statusCode === 200) {
let address = re.data.result.address_component;
resolve(address);
} else {
// getLocationInfo();
}
}
});
}
});
})
}
4 頁面調(diào)用,在需要使用的頁面引入并調(diào)用該函數(shù)即可如:home.vue頁面
<script>
import {getLocationInfo,} from "../../utils/index.js";
onReady() {
this.onGetArea(
},
methods:{
async onGetArea() {
let address = await getLocationInfo()
}
}
題外話,如果僅需要經(jīng)緯度,可以直接使用uni.getLocation獲取到