uniapp+ Vue3 +ts引入高德地图小程序SDK
小程序平台:api默认不返回详细地址中文描述。需要中文地址有2种方式:1、使用高德地图小程序sdk,在app和微信上都可以获得中文地址
前提:已经安装微信小程序开发工具,uniapp项目已经创建
1. 获取高德Key
2. 下载并安装微信小程序插件
解压后得到 amap-wx.js 文件,在创建的项目uniapp中,新建一个名为 libs 目录,将 amap-wx.js 文件拷贝到 libs 的本地目录下。
3. 设置安全通讯域名
为了保证高德小程序插件中提供的功能的正常使用,需要设置安全域名。
登录微信公众平台,在 “设置”->“开发设置” 中设置 request 合法域名,将 https://restapi.amap.com 中添加进去,如下图所示:
4. 引入SDK
import 方式导入js 模块需要在js文件中声明 export 导出,查看amap-wx.130.js文件发现文件末尾的导出是这样写的
module.exports.AMapWX=AMapWX;
这种导出方式对应的是Vue 2,在Vue 3项目中我们需要进行如下修改。
// module.exports.AMapWX=AMapWX;
export default { AMapWX };
5. 使用API
<template>
<button @click="getLocation">获取地理位置</button>
<button @click="getWeather">获取实时天气数据</button>
</template>
<script lang="ts" name="" setup>
import amap from '../../libs/amap-wx.130.js'
import { onBeforeMount, reactive } from 'vue'
let test = reactive({
amapPlugin: null,
key: '95c26c29f8e734e13bb19d55a2da99a4',
addressName: '',
weather: {
hasData: false,
data: []
}
})
onBeforeMount(()=>{
test.amapPlugin = new amap.AMapWX({
key: test.key
});
})
//获取地理位置
function getLocation(){
uni.showLoading({
title: '获取信息中'
});
test.amapPlugin.getRegeo({
success: (data) => {
console.log(data)
// test.addressName = data[0].name;
uni.hideLoading();
}
});
}
//获取实时天气数据
function getWeather() {
uni.showLoading({
title: '获取信息中'
});
test.amapPlugin.getWeather({
success: (data) => {
console.log(data);
uni.hideLoading();
test.weather.hasData = true;
}
});
}
</script>