1. Preface
In today's digital age, weather forecasting functions play an important role in many applications. By integrating the weather API provided by GUDE Maps, we can easily implement this feature in our SpringBoot project, providing users with real-time and weather information for the next few days. This article will introduce in detail how to integrate the weather forecasting functions of Gaode Maps in the SpringBoot project, including key steps such as environment construction, code implementation, and timing task setting to ensure that everyone can successfully implement functions according to the tutorial.
2. Environment construction
(I) Create SpringBoot Project
-
Using Spring Initializr
- accessSpring Initializrwebsite.
- Select project metadata, such as project name, package name, etc.
- Add dependencies:
Spring Web
、Spring Boot DevTools
(Optional, convenient for hot deployment during development). - Click the "Generate" button to download the project compression package, unzip it and import it into your IDE (such as IntelliJ IDEA or Eclipse).
Project structure example
spring-boot-weather ├── src │ ├── main │ │ ├── java │ │ │ └── │ │ │ ├── controller │ │ │ ├── service │ │ │ ├── entity │ │ │ ├── config │ │ │ └── │ │ └── resources │ │ ├── │ │ └── static │ └── test │ └── java │ └── │ └── └──
(II) Add dependencies
existAdd necessary dependencies to the file to ensure that the project can use features such as Spring Web and timing tasks.
<dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId></groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
(III) Application for Gaode Map API
-
Register a Gaode Open Platform Account
- accessGaode Open PlatformOfficial website, register an account and log in.
- Create an app in the Console to get
API Key
. ShouldKey
The weather API will be used to subsequently call the Gaode Map.
-
Configuration
- Will be obtained
API Key
and the URL of the weather API are configured toin the file.
- Will be obtained
amap-weather-config: weatherurl: /v3/weather/weatherInfo key: YOUR_API_KEY
3. Code implementation
(I) Configuration class
Create a configuration classAmapWeatherConfig
, used for readingGaode Map Weather API configuration.
package ; import ; import ; import ; import ; @Configuration @ConfigurationProperties(prefix = "amap-weather-config") @Getter @Setter public class AmapWeatherConfig { private String weatherurl; private String key; }
(II) Entity Class
Define two entity classesLive
andWeatherForecast
, used to store real-time weather and forecast weather data respectively.
Real-time weather entity categoryLive
package ; import ; @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; }
Forecast weather entity categoryWeatherForecast
package ; import ; @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; }
(III) Service layer
createWeatherService
Class, used to call the weather API of Gaode Map and encapsulate the returned data into the entity class.
package ; import ; import ; import ; import ; import ; import .slf4j.Slf4j; import .; import ; import ; import ; import ; import ; import ; import ; import ; @Service @Slf4j public class WeatherService { @Autowired private RestTemplate restTemplate; @Autowired private AmapWeatherConfig amapWeatherConfig; /** * Get real-time weather * * @param adcode City code * @return Real-time weather entity class */ public Live getLiveWeather(String adcode) { String sendUrl = () + "?key=" + () + "&city=" + adcode + "&extensions=base"; ResponseEntity<GaoDeResult> responseEntity = (sendUrl, ); // Request exception, possibly due to network or other reasons HttpStatus statusCode = (); if (!(statusCode)) { ("Request for Gaode interface error"); return null; } // Request failed GaoDeResult gaoDeResult = (); String status = (); if (!()) { ("Request for Gaode interface failed"); return null; } List<Live> lives = (); if ((lives)) { return null; } // Live weather return (0); } /** * Get weather forecasts for the next few days * * @param adcode City code * @return Weather Forecast List */ public List<WeatherForecast> getForecastWeather(String adcode) { String sendUrl = () + "?key=" + () + "&city=" + adcode + "&extensions=all"; ResponseEntity<GaoDeResult> responseEntity = (sendUrl, ); // Request exception, possibly due to network or other reasons HttpStatus statusCode = (); if (!(statusCode)) { ("Request for Gaode interface error"); return (); } // Request failed GaoDeResult gaoDeResult = (); String status = (); if (!()) { ("Request for Gaode interface failed"); return (); } List<Forecast> forecasts = (); if ((forecasts)) { return (); } // Forecast weather Forecast forecast = (0); List<WeatherForecast> weatherForecastList = new ArrayList<>(); List<> casts = (); for ( cast : casts) { WeatherForecast weatherForecast = new WeatherForecast(); (()); (()); (()); (()); (()); (()); ((())); (()); ((())); (()); (()); (()); (()); (()); (()); (()); (weatherForecast); } return weatherForecastList; } }
(IV) Entity classes GaoDeResult and Forecast
The data structure returned by the Gaode Map API is relatively complex and needs to be defined.GaoDeResult
andForecast
Classes to receive and process this data.
GaoDeResult
kind
package ; import ; import ; import ; @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
kind
package ; import ; import ; import ; @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; } }
(V) Controller layer
createWeatherController
Class, used to process front-end requests and call the service layer method to obtain weather data.
package ; import ; import ; import ; import ; import .*; import ; @RestController @RequestMapping("/weather") public class WeatherController { @Autowired private WeatherService weatherService; /** * Get real-time weather * * @param adcode City code * @return Real-time weather data */ @GetMapping("/live") public Live getLiveWeather(@RequestParam String adcode) { return (adcode); } /** * Get weather forecasts for the next few days * * @param adcode City code * @return Weather Forecast Data */ @GetMapping("/forecast") public List<WeatherForecast> getForecastWeather(@RequestParam String adcode) { return (adcode); } }
(VI) Timed tasks
In order to regularly update weather data, Spring's timing task feature can be used. createWeatherTask
class, set timing tasks.
package ; import ; import ; import ; import ; import ; import ; import ; @Component public class WeatherTask { @Autowired private WeatherService weatherService; // Weather data is updated at 3 am every day @Scheduled(cron = "0 0 3 * * ?") public void updateWeatherData() { // Suppose we update the weather data in Beijing, the city code of Beijing is 110,000 String adcode = "110000"; // Update real-time weather Live liveWeather = (adcode); if (liveWeather != null) { // Store real-time weather data in the database or cache ("Real-time weather data has been updated:" + liveWeather); } // Update weather forecasts for the next few days List<WeatherForecast> forecastWeatherList = (adcode); if (!()) { // Store weather forecast data in database or cache ("Weather forecast data has been updated:" + forecastWeatherList); } } }
(VII) Tool classes WeatherConstant and WeatherType
To facilitate processing of weather data, createWeatherConstant
Classes are used to define constants,WeatherType
Classes are used to handle mappings of weather types.
WeatherConstant
kind
package ; public class WeatherConstant { public static final String SUCCESS = "1"; }
WeatherType
kind
package ; import ; public enum WeatherType { SUNNY("clear", "01"), CLOUDY("partly cloudy", "02"), OVERCAST("Negative", "03"), LIGHT_RAIN("Little Rain", "04"), MODERATE_RAIN("Moderate Rain", "05"), HEAVY_RAIN("heavy rain", "06"), STORM("rainstorm", "07"), FOG("fog", "08"), HAZE("haze", "09"), SAND("Sandstorm", "10"), WIND("Super Wind", "11"), SNOW("Snow", "12"); @Getter private final String description; @Getter private final String code; WeatherType(String description, String code) { = description; = code; } public static String getCodeByDes(String description) { for (WeatherType type : ()) { if (().equals(description)) { return (); } } return ""; } }
4. Testing and running
(I) Start the project
Run in IDEWeatherApplication
Classicmain
Method, start the SpringBoot project.
(II) Test interface
Use Postman or browser to access the following interfaces for testing:
-
Real-time weather interface:
http://localhost:8080/weather/live?adcode=110000
-
Weather forecast interface:
http://localhost:8080/weather/forecast?adcode=110000
(III) View scheduled tasks
Check the console output, confirm whether the timing task is running normally and whether the weather data is updated on time.
5. Summary
Through the detailed steps in this article, we successfully integrated the weather forecasting function of Gaode Map in our SpringBoot project. From environment construction to code implementation, to timing tasks setting, each step is clear and clear to ensure that everyone can start directly following the tutorial. In actual development, functions can be further optimized and expanded according to needs, such as storing weather data into a database, or providing users with weather query services in more cities.
The above is the detailed content of SpringBoot integrating Gaode Map to implement weather forecasting functions. For more information about SpringBoot Gaode Map weather forecasting, please pay attention to my other related articles!