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