基于Vue.js和高德地图API来实现一个简易的天气预报

2,700 阅读4分钟

今天就让我们来使用 Vue.js 和高德地图开放平台提供的 API,实现一个关于天气预报的小demo,实时查询当前城市的天气以及未来三天的天气预测,且实现切换城市查询。实现效果如下;

PixPin_2024-12-15_00-13-38.gif

准备工作

既然要使用真实的数据,那么就需要用到高德地图开放平台提供的天气查询 API,先高德地图api注册为开发者。然后点击文档与支持,选择JS API。

image.png

然后登录到控制台创建一个应用并且添加一个key,服务平台为Web端(JS API)。 16b5ba85e6c5f128b699fe8d521bb67.jpg

终端npm create vite@latest使用vite创建项目,npm install下载该项目需要用的包,npm run dev运行项目。

image.png

将天气预报的功能全部开发在weather.vue里面,再将这个组件import weather from "./components/weather.vue"引入到app.vue中。

image.png

js代码概览

image.png

具体代码步骤实现

开始weather.vue里面的代码了。

html 部分

<div>
    // 头部
    <div class="head">
      <div class="city-name">
        <i class="iconfont icon-dingwei"></i>
        {{ state.city }}
      </div>
      <div @click="toggle" class="city-change">
        <i class="iconfont icon-24gf-city3"></i>
        切换城市
      </div>
    </div>
    
    // 中间部分实时温度
    <div class="main">
      <div class="weather-info">
        <p class="temp">{{ state.weather.temperature }}℃</p>
        <div class="info">{{ state.weather.weather }}</div>
        <div class="detail">
          <div class="item">
            <i class="iconfont icon-shuidi"></i>
            <span>湿度</span>
            <span>{{ state.weather.humidity }}</span>
          </div>
          <div class="item">
            <i class="iconfont icon-feng"></i>
            <span>风向</span>
            <span>{{ state.weather.windDirection }}</span>
          </div>
          <div class="item">
            <i class="iconfont icon-fengli"></i>
            <span>风力</span>
            <span>{{ state.weather.windPower }}</span>
          </div>
        </div>
      </div>
      
      // 未来三日的天气预报
      <div class="future">
        <div class="future-title">三日天气预报</div>
        <div class="future-content">
          <div v-for="(item,i) in state.future" class="forecast">
            <p class="week">周{{ chinese[Number(item.week)-1] }}</p>
            <i :class="getWeatherIcon(item.dayWeather)"></i>
            <p><span class="left">{{ item.dayTemp }}℃</span>  <span class="right"> / {{ item.nightTemp }}℃</span></p>
          </div>
        </div>
      </div>
    </div>
    
     // 切换城市input框
    <div v-show="state.isVisible" >
      <input id="newCity" @keydown.enter="handle" type="text" v-model="state.newCity" placeholder="请输入你要查询的城市">
    </div>
  </div>

然后使用css样式美化成如下界面

image.png

js部分

接下来就是渲染其中的数据了,首先使用高德 api 来获取定位数据,查看官方文档,JS API结合 Vue 使用,首先安装Loader,如下所示,复制到当前文件终端安装。 image.png

然后复制代码粘贴; image.png

AMapLoader 是高德地图 js API 的加载器,它可以在前端项目中加载和初始化高德地图的 js API。

import AMapLoader from '@amap/amap-jsapi-loader';
import { onMounted, reactive } from 'vue'
onMounted(() => {   // 在浏览器上出现内容时候触发
  // 加载官方提供的方法
  window._AMapSecurityConfig = {
    securityJsCode: "", // 密钥
  };
  AMapLoader.load({
    key: "", // 申请好的Web端开发者Key,首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ["AMap.Scale"], //需要使用的的插件列表,如比例尺'AMap.Scale',支持添加多个如:['...','...']
  })
  
    // 加载完上面代码高德提供的服务后,执行then后面的操作
    .then((AMap) => {
      // 获取定位
      getLocalCity(AMap)  // 使用一个函数,将获取地址信息放到这个函数中
    })
})

获取城市信息

官方文档: image.png

const getLocalCity = (AMap) => {
  AMap.plugin('AMap.CitySearch', function () {
    var citySearch = new AMap.CitySearch()
    citySearch.getLocalCity(function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        // 查询成功,result即为当前所在城市信息
        console.log(result.city);  // 会打印当前城市
        state.city = result.city  //将城市改为定位获取到的城市
        getWeather(AMap)   // 获取天气
      }
    })
  })
}

image.png

利用该地址获取实时天气数据 image.png

const getWeather = (AMap) => {
  //加载天气查询插件
  AMap.plugin("AMap.Weather", function () {
    //创建天气查询实例
    var weather = new AMap.Weather();
    //执行实时天气信息查询
    weather.getLive(state.city, function (err, data) {  // 将城市替换成state.city
      console.log(err, data);  // 获取天气数据,详情见下表
      state.weather = data     // 将数据赋值给 state.weather
      getForecast(AMap)     //  后面用来获取未来三天的天气
    });
  });
}

image.png 将这一整个对象赋值给state.weather然后再state.weather.渲染到页面上。

获取未来三天天气

const getForecast = (AMap) => {
  AMap.plugin("AMap.Weather", function () {
  //创建天气查询实例
  var weather = new AMap.Weather();
  //执行实时天气信息查询
  weather.getForecast(state.city, function (err, data) {
    console.log(err, data);  
    state.future = data.forecasts // 获取天气预报数据
    
    //err 正确时返回 null
    //data 返回天气预报数据,返回数据见下表
  });
});
}

image.png

最后就是切换城市中的input框的实现;

<div v-show="state.isVisible" >
      <input id="newCity" @keydown.enter="handle" type="text" v-model="state.newCity" placeholder="请输入你要查询的城市">
</div>

添加以一个v-show方法,然后绑定一个键盘敲击事件触发handle,并用v-model获取输入的数据并将其存储到state.newCity

const handle = () => {
  state.isVisible =!state.isVisible    // 回车键将框不显示
  state.city = state.newCity    // 城市变为输入的城市
  getWeather(AMap)   // 重新获取该城市天气以及该城市未来天气
}

const toggle = () => {
  state.isVisible =!state.isVisible   // 使得点击切换城市框会显示和消失
}

以上就是实现获取定位城市,该城市的实时天气,以及未来三天的天气预测,切换查询其它城市的功能具体代码了。

总结

以上使用了Vue.js 组件化的方式来构建界面,利用高德地图 API 获取定位和天气数据,利用 Vue 的响应式机制来实时更新页面数据,通过使用官方文档中 AMapLoader 加载高德地图的JS API,使得我们能高效处理地图相关功能,希望这个小 demo 能够对你的前端开发有所帮助,同时记得给文章点点赞哦🤗。

image.png