SpringBoot整合高德地圖實(shí)現(xiàn)天氣預(yù)報(bào)功能
一、前言
在當(dāng)今數(shù)字化時(shí)代,天氣預(yù)報(bào)功能在眾多應(yīng)用中扮演著重要角色。通過(guò)整合高德地圖提供的天氣API,我們可以輕松地在自己的SpringBoot項(xiàng)目中實(shí)現(xiàn)這一功能,為用戶提供實(shí)時(shí)和未來(lái)幾天的天氣信息。本文將詳細(xì)介紹如何在SpringBoot項(xiàng)目中整合高德地圖的天氣預(yù)報(bào)功能,包括環(huán)境搭建、代碼實(shí)現(xiàn)、定時(shí)任務(wù)設(shè)置等關(guān)鍵步驟,確保大家能夠按照教程成功實(shí)現(xiàn)功能。
二、環(huán)境搭建
(一)創(chuàng)建SpringBoot項(xiàng)目
使用Spring Initializr
- 訪問(wèn) Spring Initializr 網(wǎng)站。
- 選擇項(xiàng)目元數(shù)據(jù),如項(xiàng)目名稱(chēng)、包名等。
- 添加依賴:
Spring Web
、Spring Boot DevTools
(可選,方便開(kāi)發(fā)時(shí)熱部署)。 - 點(diǎn)擊“Generate”按鈕下載項(xiàng)目壓縮包,解壓后導(dǎo)入到你的IDE(如IntelliJ IDEA或Eclipse)中。
項(xiàng)目結(jié)構(gòu)示例
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
文件中添加必要的依賴,確保項(xiàng)目能夠使用Spring Web和定時(shí)任務(wù)等功能。
<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申請(qǐng)
注冊(cè)高德開(kāi)放平臺(tái)賬號(hào)
- 訪問(wèn) 高德開(kāi)放平臺(tái) 官網(wǎng),注冊(cè)賬號(hào)并登錄。
- 在“控制臺(tái)”中創(chuàng)建應(yīng)用,獲取
API Key
。該Key
將用于后續(xù)調(diào)用高德地圖的天氣API。
配置
application.yml
- 將獲取到的
API Key
和天氣API的URL配置到application.yml
文件中。
- 將獲取到的
amap-weather-config: weatherurl: https://restapi.amap.com/v3/weather/weatherInfo key: YOUR_API_KEY
三、代碼實(shí)現(xiàn)
(一)配置類(lèi)
創(chuàng)建一個(gè)配置類(lèi)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; }
(二)實(shí)體類(lèi)
定義兩個(gè)實(shí)體類(lèi)Live
和WeatherForecast
,分別用于存儲(chǔ)實(shí)時(shí)天氣和預(yù)報(bào)天氣的數(shù)據(jù)。
實(shí)時(shí)天氣實(shí)體類(lèi)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; }
預(yù)報(bào)天氣實(shí)體類(lèi)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; }
(三)服務(wù)層
創(chuàng)建WeatherService
類(lèi),用于調(diào)用高德地圖的天氣API,并將返回的數(shù)據(jù)封裝到實(shí)體類(lèi)中。
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; /** * 獲取實(shí)時(shí)天氣 * * @param adcode 城市編碼 * @return 實(shí)時(shí)天氣實(shí)體類(lèi) */ public Live getLiveWeather(String adcode) { String sendUrl = amapWeatherConfig.getWeatherurl() + "?key=" + amapWeatherConfig.getKey() + "&city=" + adcode + "&extensions=base"; ResponseEntity<GaoDeResult> responseEntity = restTemplate.getForEntity(sendUrl, GaoDeResult.class); // 請(qǐng)求異常,可能由于網(wǎng)絡(luò)等原因 HttpStatus statusCode = responseEntity.getStatusCode(); if (!HttpStatus.OK.equals(statusCode)) { log.info("Request for Gaode interface error"); return null; } // 請(qǐng)求失敗 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; } // 實(shí)況天氣 return lives.get(0); } /** * 獲取未來(lái)幾天的天氣預(yù)報(bào) * * @param adcode 城市編碼 * @return 天氣預(yù)報(bào)列表 */ 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); // 請(qǐng)求異常,可能由于網(wǎng)絡(luò)等原因 HttpStatus statusCode = responseEntity.getStatusCode(); if (!HttpStatus.OK.equals(statusCode)) { log.info("Request for Gaode interface error"); return Collections.emptyList(); } // 請(qǐng)求失敗 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(); } // 預(yù)報(bào)天氣 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; } }
(四)實(shí)體類(lèi)GaoDeResult和Forecast
高德地圖API返回的數(shù)據(jù)結(jié)構(gòu)較為復(fù)雜,需要定義GaoDeResult
和Forecast
類(lèi)來(lái)接收和處理這些數(shù)據(jù)。
GaoDeResult
類(lèi)
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
類(lèi)
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; } }
(五)控制器層
創(chuàng)建WeatherController
類(lèi),用于處理前端請(qǐng)求,并調(diào)用服務(wù)層的方法獲取天氣數(shù)據(jù)。
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; /** * 獲取實(shí)時(shí)天氣 * * @param adcode 城市編碼 * @return 實(shí)時(shí)天氣數(shù)據(jù) */ @GetMapping("/live") public Live getLiveWeather(@RequestParam String adcode) { return weatherService.getLiveWeather(adcode); } /** * 獲取未來(lái)幾天的天氣預(yù)報(bào) * * @param adcode 城市編碼 * @return 天氣預(yù)報(bào)數(shù)據(jù) */ @GetMapping("/forecast") public List<WeatherForecast> getForecastWeather(@RequestParam String adcode) { return weatherService.getForecastWeather(adcode); } }
(六)定時(shí)任務(wù)
為了定期更新天氣數(shù)據(jù),可以使用Spring的定時(shí)任務(wù)功能。創(chuàng)建WeatherTask
類(lèi),設(shè)置定時(shí)任務(wù)。
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點(diǎn)更新天氣數(shù)據(jù) @Scheduled(cron = "0 0 3 * * ?") public void updateWeatherData() { // 假設(shè)我們更新北京的天氣數(shù)據(jù),北京的城市編碼為110000 String adcode = "110000"; // 更新實(shí)時(shí)天氣 Live liveWeather = weatherService.getLiveWeather(adcode); if (liveWeather != null) { // 將實(shí)時(shí)天氣數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)或緩存中 System.out.println("實(shí)時(shí)天氣數(shù)據(jù)已更新:" + liveWeather); } // 更新未來(lái)幾天的天氣預(yù)報(bào) List<WeatherForecast> forecastWeatherList = weatherService.getForecastWeather(adcode); if (!forecastWeatherList.isEmpty()) { // 將天氣預(yù)報(bào)數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)或緩存中 System.out.println("天氣預(yù)報(bào)數(shù)據(jù)已更新:" + forecastWeatherList); } } }
(七)工具類(lèi)WeatherConstant和WeatherType
為了方便處理天氣數(shù)據(jù),創(chuàng)建WeatherConstant
類(lèi)用于定義常量,WeatherType
類(lèi)用于處理天氣類(lèi)型的映射。
WeatherConstant
類(lèi)
package com.example.weather.common; public class WeatherConstant { public static final String SUCCESS = "1"; }
WeatherType
類(lèi)
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("大風(fēng)", "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 ""; } }
四、測(cè)試與運(yùn)行
(一)啟動(dòng)項(xiàng)目
在IDE中運(yùn)行WeatherApplication
類(lèi)的main
方法,啟動(dòng)SpringBoot項(xiàng)目。
(二)測(cè)試接口
使用Postman或?yàn)g覽器訪問(wèn)以下接口進(jìn)行測(cè)試:
- 實(shí)時(shí)天氣接口:
http://localhost:8080/weather/live?adcode=110000
- 天氣預(yù)報(bào)接口:
http://localhost:8080/weather/forecast?adcode=110000
(三)查看定時(shí)任務(wù)
查看控制臺(tái)輸出,確認(rèn)定時(shí)任務(wù)是否正常運(yùn)行,天氣數(shù)據(jù)是否按時(shí)更新。
五、總結(jié)
通過(guò)本文的詳細(xì)步驟,我們成功地在SpringBoot項(xiàng)目中整合了高德地圖的天氣預(yù)報(bào)功能。從環(huán)境搭建到代碼實(shí)現(xiàn),再到定時(shí)任務(wù)的設(shè)置,每一步都清晰明確,確保大家能夠按照教程直接上手操作。在實(shí)際開(kāi)發(fā)中,可以根據(jù)需求進(jìn)一步優(yōu)化和擴(kuò)展功能,例如將天氣數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)中,或者為用戶提供更多城市的天氣查詢服務(wù)。
以上就是SpringBoot整合高德地圖實(shí)現(xiàn)天氣預(yù)報(bào)功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot高德地圖天氣預(yù)報(bào)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
部署springboot打包不打包配置文件,配置文件為外部配置文件使用詳解
在Spring Boot項(xiàng)目中,將配置文件排除在jar包之外,通過(guò)外部配置文件來(lái)管理不同環(huán)境的配置,可以實(shí)現(xiàn)靈活的配置管理,在pom.xml文件中添加相關(guān)配置,打包時(shí)忽略指定文件,運(yùn)行時(shí)在jar包同級(jí)目錄下創(chuàng)建config文件夾,將配置文件放入其中即可2025-02-02java基于雙向環(huán)形鏈表解決丟手帕問(wèn)題的方法示例
這篇文章主要介紹了java基于雙向環(huán)形鏈表解決丟手帕問(wèn)題的方法,簡(jiǎn)單描述了丟手帕問(wèn)題,并結(jié)合實(shí)例形式給出了Java基于雙向環(huán)形鏈表解決丟手帕問(wèn)題的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11Java本地方法(JNA)詳解及常見(jiàn)問(wèn)題
JNA(Java?Native?Access)是一個(gè)開(kāi)源Java框架,用于無(wú)需編寫(xiě)JNI代碼即可動(dòng)態(tài)訪問(wèn)本地系統(tǒng)庫(kù)如Windows的dll,它允許Java程序直接調(diào)用本地方法,這篇文章主要介紹了Java本地方法(JNA)詳解及常見(jiàn)問(wèn)題,需要的朋友可以參考下2024-09-09解決springcloud阿里云OSS文件訪問(wèn)跨域問(wèn)題的實(shí)現(xiàn)
本文主要介紹了解決springcloud阿里云OSS文件訪問(wèn)跨域問(wèn)題的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06