要构建一个基于 Spring Boot 和 Leaflet 集成在线天气服务的区县当前天气 WebGIS 系统,你可以通过以下步骤来实现。这个项目的目标是使用 Spring Boot 提供天气 API,并利用 Leaflet 在前端展示天气信息。
项目结构
- 后端(Spring Boot):
- 提供天气 API,接收前端的地理位置信息(如经纬度或区县名称),然后调用外部天气 API 获取实时天气信息。
- 前端(Leaflet + HTML + JavaScript):
- 使用 Leaflet 库在地图上展示区域(区县),用户点击地图时,发送请求获取该位置的天气信息,并展示。
1. 后端开发(Spring Boot)
1.1 创建 Spring Boot 项目
首先使用 Spring Initializr 创建一个 Spring Boot 项目,选择以下依赖:
- Spring Web:用于创建 REST API。
- Spring Boot DevTools:用于开发时的热部署。
- Lombok:简化代码(如 getter、setter)。
1.2 引入外部天气 API
使用 OpenWeatherMap 或 和风天气 等天气数据源,你可以选择其中一个来获取实时天气数据。以 OpenWeatherMap 为例,你需要注册并获取一个 API Key。
API 示例:
- 获取当前天气数据的 URL:
http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API_KEY}&units=metric
创建天气服务:
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Service
public class WeatherService {
private static final String API_KEY = "your_api_key_here";
private static final String WEATHER_API_URL = "http://api.openweathermap.org/data/2.5/weather";
public String getWeather(double latitude, double longitude) {
// 构建请求 URL
String url = UriComponentsBuilder.fromHttpUrl(WEATHER_API_URL)
.queryParam("lat", latitude)
.queryParam("lon", longitude)
.queryParam("appid", API_KEY)
.queryParam("units", "metric") // 获取摄氏温度
.toUriString();
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(url, String.class);
}
}
创建天气查询接口:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WeatherController {
@Autowired
private WeatherService weatherService;
@GetMapping("/api/weather")
public ResponseEntity<String> getWeather(@RequestParam double lat, @RequestParam double lon) {
String weatherData = weatherService.getWeather(lat, lon);
return ResponseEntity.ok(weatherData);
}
}
1.3 配置 CORS(跨域请求)
如果前端和后端分开部署,你需要配置 CORS 以允许跨域请求:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://localhost:8080") // 或者设置为 "*" 允许所有域名
public class WeatherController {
// ...
}
2. 前端开发(Leaflet + HTML + JavaScript)
2.1 引入 Leaflet
在你的 HTML 文件中引入 Leaflet 库, Leaflet 是一个开源的 JavaScript 库,用于在网页上显示交互式地图。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>天气 WebGIS</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#map { height: 500px; }
#weather-info { padding: 20px; }
</style>
</head>
<body>
<div id="map"></div>
<div id="weather-info"></div>
<script>
// 创建 Leaflet 地图
var map = L.map('map').setView([39.9042, 116.4074], 11); // 默认设置为北京的经纬度
// 设置地图瓦片图层
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
// 点击地图时获取当前位置天气
map.on('click', function(e) {
var lat = e.latlng.lat;
var lon = e.latlng.lng;
// 发送请求到后端获取天气数据
$.get(`/api/weather?lat=${lat}&lon=${lon}`, function(data) {
// 假设返回的数据为 JSON 格式
var weather = JSON.parse(data);
var temp = weather.main.temp;
var description = weather.weather[0].description;
var weatherHtml = `
<h3>当前位置:${lat.toFixed(2)}, ${lon.toFixed(2)}</h3>
<p>温度:${temp}°C</p>
<p>天气描述:${description}</p>
`;
$('#weather-info').html(weatherHtml);
});
});
</script>
</body>
</html>
2.2 前端交互
- 当用户点击地图时,触发
click
事件。 - 根据点击的坐标(经纬度),发送 AJAX 请求到 Spring Boot 后端获取天气信息。
- 使用 jQuery 来处理返回的数据并展示到网页上。
3. 部署与运行
3.1 启动后端服务
在 Spring Boot 项目根目录下,使用以下命令启动应用:
mvn spring-boot:run
3.2 启动前端页面
- 如果你的前端和后端部署在同一台机器上,直接访问
http://localhost:8080
即可。 - 如果前后端分开部署,需要将前端项目部署到 HTTP 服务器上,并确保后端的 API 地址正确。
4. 功能扩展与优化
- 缓存天气数据:为了减少对外部天气 API 的请求频率,可以在后端缓存天气数据,比如缓存 5 分钟以内的天气数据。
- 显示更多天气信息:除了温度和描述,你还可以显示湿度、风速等信息。
- 根据区县名查询:可以添加功能,通过区县名称(如“北京朝阳区”)查询天气。
- 美化地图与展示:使用不同的 Leaflet 插件来增强地图的功能,如添加标记、信息窗口等。
- UI 优化:可以用 CSS 或框架如 Bootstrap 美化天气展示的样式。
通过以上步骤,你就可以实现一个基于 Spring Boot 和 Leaflet 的天气查询 WebGIS 系统,支持通过点击地图来获取指定区域的天气数据。如果有更多具体问题,随时问我!
发表回复