实现效果:
需求:根据定位功能,使用高德地图实现定位当前城市的天气预报功能。
JS API 2.0 版本提供了两种方案引入地图 JSAPI:
1. 使用官网提供的 JSAPI Loader 进行加载;
2. 以常规 JavaScript 脚本的方式加载;
注意:为避免地图数据协议和前端资源不匹配导致页面运行报错,只允许在线加载 JSAPI,禁止进行本地转存、与其它代码混合打包等用法。
JSAPI Loader是我们提供的 API 加载器,可帮助开发者快速定位、有效避免加载引用地图 JSAPI 各种错误用法,具有以下特性:
注意(您在2021年12月02日申请以后的key需要配合您的安全密钥一起使用)
JSAPI key搭配代理服务器并携带安全密钥转发(安全)
1) 引入 JSAPI 使用 Loader 之前增加代理服务器设置脚本标签,设置代理服务器域名或地址,将下面示例代码中的「您的代理服务器域名或地址」替换为您的代理服务器域名或ip地址,其中_AMapService为代理请求固定前缀,不可省略或修改。 (注意您这 个设置必须是在加载loader.js的脚本引入之前进行设置,否则设置无效。)
....... <body> <noscript> <strong>We're sorry but map-demo doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <script type="text/javascript"> window._AMapSecurityConfig = { // serviceHost:'您的代理服务器域名或地址/_AMapService', securityJsCode:"xxxxxx"//申请的密钥 } </script> </body> ......
npm i @amap/amap-jsapi-loader --save
页面引入:
import AMapLoader from "@amap/amap-jsapi-loader";
当前截取的代码是天气部分
... <div class="header-content flex align-items"> <!-- <img src="../../assets/img/index_03.png"/> --> <span class="header-left-txt" id="weather" v-if="weatherObj.nightWeather!=weatherObj.dayWeather"> {{weatherObj.nightWeather}}转{{weatherObj.dayWeather}} {{weatherObj.nightTemp?weatherObj.nightTemp+"°C":""}}<i v-show="weatherObj.dayTemp">-</i>{{weatherObj.dayTemp?weatherObj.dayTemp+"°C":""}} </span> <span class="header-left-txt" id="weather" v-else> {{weatherObj.dayWeather}} {{weatherObj.nightTemp?weatherObj.nightTemp+"°C":""}}<i v-show="weatherObj.dayTemp">-</i>{{weatherObj.dayTemp?weatherObj.dayTemp+"°C":""}} </span> <!-- <van-icon name="arrow-down" color="#fff" size="14px" class="ml10"/> --> </div> ...
// 天气 weatherObj:{ nightTemp:"",//夜间温度, dayTemp:"",//白天温度 dayWeather:"",//白天天气 nightWeather:"",//夜间天气 }
// 天气 loadWeather(city) { return new Promise((reslove, reject) => { AMapLoader.load({ key: "xxxxx", // 申请好的Web端开发者Key,首次调用 load 时必填 // version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15 plugins: ["AMap.Weather"], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 AMapUI: { // 是否加载 AMapUI,缺省不加载 version: "1.1", // AMapUI 缺省 1.1 plugins: [] // 需要加载的 AMapUI ui插件 } }).then(AMap => { //创建天气查询实例 let weather = new AMap.Weather(); //执行实时天气信息查询 weather.getForecast(city?city:"武汉市", (err, data)=> { // console.log(err, data); if(data.info=="OK"){ let forecasts = data.forecasts[0]; this.weatherObj = forecasts; console.log(this.weatherObj,"天气") }else{ console.log("获取天气失败"); } }); reslove(); }) .catch(e => { console.log(e, "高德地图加载失败"); reject(e); }); }); }
可以根据手机定位获取当前天气功能,或者可以实现切换城市获取天气。
mounted(){ this.loadWeather("武汉");//高德天气 }