当前位置: 代码网 > it编程>编程语言>Java > SpringBoot整合高德地图实现天气预报功能

SpringBoot整合高德地图实现天气预报功能

2025年03月26日 Java 我要评论
一、前言在当今数字化时代,天气预报功能在众多应用中扮演着重要角色。通过整合高德地图提供的天气api,我们可以轻松地在自己的springboot项目中实现这一功能,为用户提供实时和未来几天的天气信息。本

一、前言

在当今数字化时代,天气预报功能在众多应用中扮演着重要角色。通过整合高德地图提供的天气api,我们可以轻松地在自己的springboot项目中实现这一功能,为用户提供实时和未来几天的天气信息。本文将详细介绍如何在springboot项目中整合高德地图的天气预报功能,包括环境搭建、代码实现、定时任务设置等关键步骤,确保大家能够按照教程成功实现功能。

二、环境搭建

(一)创建springboot项目

  • 使用spring initializr

    • 访问 spring initializr 网站。
    • 选择项目元数据,如项目名称、包名等。
    • 添加依赖:spring webspring boot devtools(可选,方便开发时热部署)。
    • 点击“generate”按钮下载项目压缩包,解压后导入到你的ide(如intellij idea或eclipse)中。
  • 项目结构示例

spring-boot-weather
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example.weather
│   │   │       ├── controller
│   │   │       ├── service
│   │   │       ├── entity
│   │   │       ├── config
│   │   │       └── weatherapplication.java
│   │   └── resources
│   │       ├── application.yml
│   │       └── static
│   └── test
│       └── java
│           └── com.example.weather
│               └── weatherapplicationtests.java
└── pom.xml

(二)添加依赖

pom.xml文件中添加必要的依赖,确保项目能够使用spring web和定时任务等功能。

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-devtools</artifactid>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupid>org.projectlombok</groupid>
        <artifactid>lombok</artifactid>
        <optional>true</optional>
    </dependency>
</dependencies>

(三)高德地图api申请

  • 注册高德开放平台账号

    • 访问 高德开放平台 官网,注册账号并登录。
    • 在“控制台”中创建应用,获取api key。该key将用于后续调用高德地图的天气api。
  • 配置application.yml

    • 将获取到的api key和天气api的url配置到application.yml文件中。
amap-weather-config:
  weatherurl: https://restapi.amap.com/v3/weather/weatherinfo
  key: your_api_key

三、代码实现

(一)配置类

创建一个配置类amapweatherconfig,用于读取application.yml中的高德地图天气api配置。

package com.example.weather.config;

import lombok.getter;
import lombok.setter;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.context.annotation.configuration;

@configuration
@configurationproperties(prefix = "amap-weather-config")
@getter
@setter
public class amapweatherconfig {
    private string weatherurl;
    private string key;
}

(二)实体类

定义两个实体类liveweatherforecast,分别用于存储实时天气和预报天气的数据。

实时天气实体类live

package com.example.weather.entity;

import lombok.data;

@data
public class live {
    private string province;
    private string city;
    private string adcode;
    private string weather;
    private string temperature;
    private string winddirection;
    private string windpower;
    private string humidity;
    private string reporttime;
}

预报天气实体类weatherforecast

package com.example.weather.entity;

import lombok.data;

@data
public class weatherforecast {
    private string province;
    private string city;
    private string adcode;
    private string date;
    private string week;
    private string dayweather;
    private string dayweatherimg;
    private string nightweather;
    private string nightweatherimg;
    private string daytemp;
    private string nighttemp;
    private string daywind;
    private string nightwind;
    private string daypower;
    private string nightpower;
    private string reporttime;
}

(三)服务层

创建weatherservice类,用于调用高德地图的天气api,并将返回的数据封装到实体类中。

package com.example.weather.service;

import com.example.weather.config.amapweatherconfig;
import com.example.weather.entity.live;
import com.example.weather.entity.weatherforecast;
import com.example.weather.common.weatherconstant;
import com.example.weather.enums.weathertype;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.collections4.collectionutils;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.stereotype.service;
import org.springframework.web.client.resttemplate;

import java.util.arraylist;
import java.util.collections;
import java.util.list;

@service
@slf4j
public class weatherservice {
    @autowired
    private resttemplate resttemplate;

    @autowired
    private amapweatherconfig amapweatherconfig;

    /**
     * 获取实时天气
     *
     * @param adcode 城市编码
     * @return 实时天气实体类
     */
    public live getliveweather(string adcode) {
        string sendurl = amapweatherconfig.getweatherurl() +
                "?key=" + amapweatherconfig.getkey() +
                "&city=" + adcode +
                "&extensions=base";
        responseentity<gaoderesult> responseentity = resttemplate.getforentity(sendurl, gaoderesult.class);
        // 请求异常,可能由于网络等原因
        httpstatus statuscode = responseentity.getstatuscode();
        if (!httpstatus.ok.equals(statuscode)) {
            log.info("request for gaode interface error");
            return null;
        }
        // 请求失败
        gaoderesult gaoderesult = responseentity.getbody();
        string status = gaoderesult.getstatus();
        if (!status.equals(weatherconstant.success)) {
            log.info("request for gaode interface failed");
            return null;
        }

        list<live> lives = gaoderesult.getlives();
        if (collectionutils.isempty(lives)) {
            return null;
        }
        // 实况天气
        return lives.get(0);
    }

    /**
     * 获取未来几天的天气预报
     *
     * @param adcode 城市编码
     * @return 天气预报列表
     */
    public list<weatherforecast> getforecastweather(string adcode) {
        string sendurl = amapweatherconfig.getweatherurl() +
                "?key=" + amapweatherconfig.getkey() +
                "&city=" + adcode +
                "&extensions=all";
        responseentity<gaoderesult> responseentity = resttemplate.getforentity(sendurl, gaoderesult.class);
        // 请求异常,可能由于网络等原因
        httpstatus statuscode = responseentity.getstatuscode();
        if (!httpstatus.ok.equals(statuscode)) {
            log.info("request for gaode interface error");
            return collections.emptylist();
        }

        // 请求失败
        gaoderesult gaoderesult = responseentity.getbody();
        string status = gaoderesult.getstatus();
        if (!status.equals(weatherconstant.success)) {
            log.info("request for gaode interface failed");
            return collections.emptylist();
        }

        list<forecast> forecasts = gaoderesult.getforecasts();
        if (collectionutils.isempty(forecasts)) {
            return collections.emptylist();
        }

        // 预报天气
        forecast forecast = forecasts.get(0);
        list<weatherforecast> weatherforecastlist = new arraylist<>();
        list<forecast.cast> casts = forecast.getcasts();
        for (forecast.cast cast : casts) {
            weatherforecast weatherforecast = new weatherforecast();
            weatherforecast.setprovince(forecast.getprovince());
            weatherforecast.setcity(forecast.getcity());
            weatherforecast.setadcode(forecast.getadcode());
            weatherforecast.setdate(cast.getdate());
            weatherforecast.setweek(cast.getweek());
            weatherforecast.setdayweather(cast.getdayweather());
            weatherforecast.setdayweatherimg(weathertype.getcodebydes(cast.getdayweather()));
            weatherforecast.setnightweather(cast.getnightweather());
            weatherforecast.setnightweatherimg(weathertype.getcodebydes(cast.getnightweather()));
            weatherforecast.setdaytemp(cast.getdaytemp());
            weatherforecast.setnighttemp(cast.getnighttemp());
            weatherforecast.setdaywind(cast.getdaywind());
            weatherforecast.setnightwind(cast.getnightwind());
            weatherforecast.setdaypower(cast.getdaypower());
            weatherforecast.setnightpower(cast.getnightpower());
            weatherforecast.setreporttime(forecast.getreporttime());
            weatherforecastlist.add(weatherforecast);
        }
        return weatherforecastlist;
    }
}

(四)实体类gaoderesult和forecast

高德地图api返回的数据结构较为复杂,需要定义gaoderesultforecast类来接收和处理这些数据。

gaoderesult

package com.example.weather.entity;

import com.fasterxml.jackson.annotation.jsonproperty;
import lombok.data;

import java.util.list;

@data
public class gaoderesult {
    private string status;
    private string info;
    private string infocode;
    @jsonproperty("lives")
    private list<live> lives;
    @jsonproperty("forecasts")
    private list<forecast> forecasts;
}

forecast

package com.example.weather.entity;

import com.fasterxml.jackson.annotation.jsonproperty;
import lombok.data;

import java.util.list;

@data
public class forecast {
    private string province;
    private string city;
    private string adcode;
    private string reporttime;
    @jsonproperty("casts")
    private list<cast> casts;

    @data
    public static class cast {
        private string date;
        private string week;
        private string dayweather;
        private string nightweather;
        private string daytemp;
        private string nighttemp;
        private string daywind;
        private string nightwind;
        private string daypower;
        private string nightpower;
    }
}

(五)控制器层

创建weathercontroller类,用于处理前端请求,并调用服务层的方法获取天气数据。

package com.example.weather.controller;

import com.example.weather.entity.live;
import com.example.weather.entity.weatherforecast;
import com.example.weather.service.weatherservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;

import java.util.list;

@restcontroller
@requestmapping("/weather")
public class weathercontroller {
    @autowired
    private weatherservice weatherservice;

    /**
     * 获取实时天气
     *
     * @param adcode 城市编码
     * @return 实时天气数据
     */
    @getmapping("/live")
    public live getliveweather(@requestparam string adcode) {
        return weatherservice.getliveweather(adcode);
    }

    /**
     * 获取未来几天的天气预报
     *
     * @param adcode 城市编码
     * @return 天气预报数据
     */
    @getmapping("/forecast")
    public list<weatherforecast> getforecastweather(@requestparam string adcode) {
        return weatherservice.getforecastweather(adcode);
    }
}

(六)定时任务

为了定期更新天气数据,可以使用spring的定时任务功能。创建weathertask类,设置定时任务。

package com.example.weather.task;

import com.example.weather.entity.live;
import com.example.weather.entity.weatherforecast;
import com.example.weather.service.weatherservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;

import java.util.list;

@component
public class weathertask {
    @autowired
    private weatherservice weatherservice;

    // 每天凌晨3点更新天气数据
    @scheduled(cron = "0 0 3 * * ?")
    public void updateweatherdata() {
        // 假设我们更新北京的天气数据,北京的城市编码为110000
        string adcode = "110000";

        // 更新实时天气
        live liveweather = weatherservice.getliveweather(adcode);
        if (liveweather != null) {
            // 将实时天气数据存储到数据库或缓存中
            system.out.println("实时天气数据已更新:" + liveweather);
        }

        // 更新未来几天的天气预报
        list<weatherforecast> forecastweatherlist = weatherservice.getforecastweather(adcode);
        if (!forecastweatherlist.isempty()) {
            // 将天气预报数据存储到数据库或缓存中
            system.out.println("天气预报数据已更新:" + forecastweatherlist);
        }
    }
}

(七)工具类weatherconstant和weathertype

为了方便处理天气数据,创建weatherconstant类用于定义常量,weathertype类用于处理天气类型的映射。

weatherconstant

package com.example.weather.common;

public class weatherconstant {
    public static final string success = "1";
}

weathertype

package com.example.weather.enums;

import lombok.getter;

public enum weathertype {
    sunny("晴", "01"),
    cloudy("多云", "02"),
    overcast("阴", "03"),
    light_rain("小雨", "04"),
    moderate_rain("中雨", "05"),
    heavy_rain("大雨", "06"),
    storm("暴雨", "07"),
    fog("雾", "08"),
    haze("霾", "09"),
    sand("沙尘暴", "10"),
    wind("大风", "11"),
    snow("雪", "12");

    @getter
    private final string description;
    @getter
    private final string code;

    weathertype(string description, string code) {
        this.description = description;
        this.code = code;
    }

    public static string getcodebydes(string description) {
        for (weathertype type : weathertype.values()) {
            if (type.getdescription().equals(description)) {
                return type.getcode();
            }
        }
        return "";
    }
}

四、测试与运行

(一)启动项目

在ide中运行weatherapplication类的main方法,启动springboot项目。

(二)测试接口

使用postman或浏览器访问以下接口进行测试:

  • 实时天气接口http://localhost:8080/weather/live?adcode=110000
  • 天气预报接口http://localhost:8080/weather/forecast?adcode=110000

(三)查看定时任务

查看控制台输出,确认定时任务是否正常运行,天气数据是否按时更新。

五、总结

通过本文的详细步骤,我们成功地在springboot项目中整合了高德地图的天气预报功能。从环境搭建到代码实现,再到定时任务的设置,每一步都清晰明确,确保大家能够按照教程直接上手操作。在实际开发中,可以根据需求进一步优化和扩展功能,例如将天气数据存储到数据库中,或者为用户提供更多城市的天气查询服务。

以上就是springboot整合高德地图实现天气预报功能的详细内容,更多关于springboot高德地图天气预报的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com