通常の開発では緯度と経度はuni.getLocationでしか取得できず、WeChat では具体的な地理的位置は得られませんが、現時点では逆コンパイルによって詳細な住所を取得できます。操作は次のとおりです
ステップ 1: Tencent Map に移動してキーTencent Map
を申請します。コンソールで ==> アプリケーション管理 ==> マイ アプリケーション ==> アプリケーションの作成 ==> キーの追加 ==> 必須フィールドに加えて、WebserviceAPI を確認します。
ステップ 2: WeChat ミニ プログラム JavaScriptSDK をダウンロードする
アドレス:ミニプログラム SDK
ステップ 3: 安全なドメイン名設定を構成する
WeChat公式アカウントにログイン -> 開発 -> 開発設定 -> サーバードメイン名 ->https://apis.map.qq.com
リクエストの正当なドメイン名を入力します
ステップ 4: 2 番目のステップでダウンロードした sdk.js をディレクトリに置きます。ここでは圧縮バージョン (min) を使用します。
ステップ 5: 必要なページに導入する
var QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js')
次に、新しいインスタンス オブジェクトがあり、このオブジェクトにはreverseGeocoder という メソッドがあり、 uni.getLocationで取得した経度と緯度を渡すことで詳細な住所を取得します。早速、コードに進みましょう。
<script>
var QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js')
export default {
data() {
return {
}
},
onLoad() {
this.getLocation()
},
onShow() {
},
onReady() {
},
methods: {
// 获取当前位置
getLocation(){
const _this = this
uni.authorize({
scope: 'scope.userLocation',
success() {
let location = {
longitude: 0,
latitude: 0,
province: "",
city: "",
area: "",
street: "",
address: "",
};
uni.getLocation({
type: 'gcj02',
geocode: true,
success: function(res) {
console.log(res,'获取经纬度');
uni.setStorageSync('latitude', _this.latitude)
uni.setStorageSync('longitude', _this.longitude)
location.longitude = res.longitude;
location.latitude = res.latitude;
const qqmapsdk = new QQMapWX({
key: '你在腾讯地图申请的key' //申请的key
});
qqmapsdk.reverseGeocoder({
location,
success: function(res) {
console.log(res, '获取地址');
let info = res.result;
location.province = info.address_component.province;
location.city = info.address_component.city;
location.area = info.address_component.district;
location.street = info.address_component.street;
location.address = info.address;
console.log(location, '地址');
},
});
},
fail: function(err) {
_this.$util.modal({
c: '获取位置失败,请重新进入小程序并同意获取位置',
}, () => wx.openSetting())
}
})
},
fail: () => {
this.tipsAddress()
}
})
},
tipsAddress () {
this.$util.showModal({
content: '为了正常使用,请授权「位置信息」- 「使用小程序时允许」',
showCancel: false,
}).then(() => {
wx.openSetting({
success: (res) => {
if (res.errMsg === 'openSetting:ok') {
console.log(res.authSetting, 'res');
if (!res.authSetting['scope.userLocation']) {
this.tipsAddress()
} else {
this.getLocation()
}
}
},
fail: () => {
this.tipsAddress()
}
})
})
},
},
}
</script>