如何使用高德地图查询天气,使用lunar-typescript查询万年历(黄历)(纯前端)

362 阅读2分钟
  1. 使用高德地图的api获取天气信息,需要先注册高德地图开发者账号,console.amap.com/dev/key/app 新建应用,获取key和秘钥。 image.png最新的文档表明密钥需要和key一起使用。
  2. 在项目代码中需要安装 "@amap/amap-jsapi-loader": "^1.0.1"后,在组件中引入 AMapLoader 对象,然后调用其方法获取天气信息
import AMapLoader from '@amap/amap-jsapi-loader';
// 天气
const localTime = ref('00:00')
const weatherData = ref({
    city: '',
    weather: '',
    temperature: '',
    windPower: '',
    windDirection: '',
    humidity: '',
    nightTemp: '',
    dayTemp: '',
    picUrl: ''
})
const initAMap = () => {
    AMapLoader.load({
      key: '你自己的key',               // 申请好的Web端开发者Key,首次调用 load 时必填
      version: '2.0',                  // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
      plugins: ['AMap.Weather']       // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    }).then((AMap) => {
      AMap.plugin('AMap.CitySearch', function() {
        const citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功,result即为当前所在城市信息
            console.log(result, '当前城市')
            //加载天气查询插件
            AMap.plugin('AMap.Weather', function() {
              var weather = new AMap.Weather();
              //查询实时天气信息
              weather.getLive(result.city, function(err, data) {
                console.log(err, data, '实时天气信息')
                const {
                  city,
                  weather,
                  temperature,
                  windPower,
                  windDirection,
                  humidity
                } = data || {}
                weatherData.value.city = city
                weatherData.value.weather = weather
                weatherData.value.temperature = temperature
                weatherData.value.windPower = windPower
                weatherData.value.windDirection = windDirection
                weatherData.value.humidity = humidity
                weatherData.value.picUrl = '/no.png'
                if (weather.includes('晴')) weatherData.value.picUrl = '/qing.png'
                if (weather.includes('云')) weatherData.value.picUrl = '/duoyun.png'
                if (weather.includes('阴')) weatherData.value.picUrl = '/yin.png'
                if (weather.includes('雨')) weatherData.value.picUrl = '/yu.png'
                if (weather.includes('雾')) weatherData.value.picUrl = '/wu.png'
                if (weather.includes('霾')) weatherData.value.picUrl = '/mai.png'
                if (weather.includes('雪')) weatherData.value.picUrl = '/xue.png'
                if (weather.includes('雨夹雪')) weatherData.value.picUrl = '/yujiaxue.png'
                if (weather.includes('风')) weatherData.value.picUrl = '/dafeng.png'
                if (weather.includes('冰')) weatherData.value.picUrl = '/bingbao.png'
                if (weather.includes('雷')) weatherData.value.picUrl = '/leizhenyu.png'
                if (weather.includes('沙')) weatherData.value.picUrl = '/shachenbao.png'
              })
              weather.getForecast(result.city, function(err, data) {
                console.log(err, data, '未来天气信息')
                const {
                  forecasts
                } = data || {}
                const today = forecasts[0]
                weatherData.value.nightTemp = today.nightTemp
                weatherData.value.dayTemp = today.dayTemp
              })
            })
          }
        })
      })
    })
  }
  onMounted(() => {
      setInterval(() => {
          localTime.value = new Date().toLocaleTimeString()
        }, 1000);
      initAMap()
      initLunar()
  })
  1. 要生效的话还需要在项目的index.html中配置密钥
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="text/javascript">
      window._AMapSecurityConfig = {
        securityJsCode: "密钥",
      };
    </script>
    <title>Vite + Vue</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
  1. 具体api官方文档地址 lbs.amap.com/api/javascr…
  2. 前端获取农历,节气,农历,公历节日等信息,可以使用组件库 lunar-typescript或者lunar-javascript 官方文档:6tail.cn/calendar/ap… image.png
  3. 安装 "@amap/amap-jsapi-loader": "^1.0.1", 在组件中按需引入需要的对象
import { Lunar, LunarMonth } from 'lunar-typescript';
// 黄历
const lunarData = reactive({
    date: '',
    week: '',
    yearInGanZhi: '',
    yearShengXiao: '',
    monthInChinese: '',
    lunarDay: '',
    fesOrJieqi: ''
 })
 const initLunar = () => {
    const lunar = Lunar.fromDate(new Date())
    const n = new Date()
    const y = n.getFullYear()
    const m = n.getMonth() + 1
    const d = n.getDate()
    lunarData.date = `${y}/${m}/${d}`
    const day = n.getDay()
    const weekL = ['日', '一', '二', '三', '四', '五', '六']
    lunarData.week = weekL[day]
    lunarData.yearInGanZhi = lunar.getYearInGanZhi()
    lunarData.yearShengXiao = lunar.getYearShengXiao()
    lunarData.monthInChinese = lunar.getMonthInChinese()
    lunarData.lunarDay = lunar.getDayInChinese()
    let curFesList = lunar.getFestivals()
    let curFes = ''
    if (curFesList.length) {
      curFes = curFesList[0]
    }
    let curJieqi = ''
    const jq = lunar.getCurrentJieQi()
    if (jq) {
      curJieqi = jq.getName()
    }
    lunarData.fesOrJieqi = curFes || curJieqi
  }
  1. 最后效果 image.png