UNIAPP前端配合thinkphp5后端通过高德API获取当前城市天气预报

如何通过 UniApp 前端项目与 ThinkPHP5 后端结合高德天气 API 获取天气预报信息。我们将分为前端和后端两部分进行实现。以下是一个完整的代码.


一、项目结构

project/
├── frontend/ (UniApp 项目)
│   ├── pages/
│   │   └── weather/
│   │       ├── index.vue
├── backend/ (ThinkPHP5 项目)
│   ├── application/
│   │   ├── controller/
│   │   │   └── Weather.php
│   │   ├── route/
│   │   │   └── route.php
│   ├── public/
│   │   └── index.php

二、后端(ThinkPHP5)

1. 配置高德 API Key

application/extra/config.php 中添加高德 API Key:

return [
    'amap_api_key' => 'YOUR_AMAP_API_KEY', // 替换为你的高德 API Key
];

2. 创建控制器 Weather.php

application/controller/Weather.php 中编写获取天气的逻辑:

<?php
namespace app\controller;

use think\Controller;
use think\Request;

class Weather extends Controller
{
    public function getWeather(Request $request)
    {
        // 获取前端传递的经纬度参数
        $longitude = $request->param('longitude');
        $latitude = $request->param('latitude');

        if (!$longitude || !$latitude) {
            return json(['code' => 400, 'message' => '经纬度参数缺失']);
        }

        // 高德天气 API URL
        $apiKey = config('amap_api_key');
        $url = "https://restapi.amap.com/v3/weather/weatherInfo?output=json&key={$apiKey}&location={$longitude},{$latitude}";

        // 调用高德 API
        $response = file_get_contents($url);
        $data = json_decode($response, true);

        if ($data['status'] == 1 && isset($data['lives'])) {
            return json(['code' => 200, 'data' => $data['lives'][0]]);
        } else {
            return json(['code' => 500, 'message' => '获取天气失败']);
        }
    }
}

3. 配置路由

application/route/route.php 中配置路由:

use think\facade\Route;

Route::get('weather/get', 'Weather/getWeather');

三、前端(UniApp)

1. 获取用户位置并请求天气数据

pages/weather/index.vue 中实现获取用户位置并通过后端接口获取天气数据:

<template>
  <view class="container">
    <view v-if="loading" class="loading">加载中...</view>
    <view v-else class="weather-info">
      <view class="location">{{ weather.city }}</view>
      <view class="temperature">{{ weather.temperature }}°C</view>
      <view class="description">{{ weather.weather }}</view>
      <view class="wind">风向:{{ weather.winddirection }},风速:{{ weather.windspeed }} km/h</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: true,
      weather: {}
    };
  },
  onLoad() {
    this.getLocation();
  },
  methods: {
    getLocation() {
      uni.getLocation({
        type: 'gcj02', // 高德地图使用的坐标系
        success: (res) => {
          const { latitude, longitude } = res;
          this.fetchWeather(longitude, latitude);
        },
        fail: () => {
          uni.showToast({
            title: '获取位置失败,请检查权限',
            icon: 'none'
          });
          this.loading = false;
        }
      });
    },
    fetchWeather(longitude, latitude) {
      uni.request({
        url: 'http://www.xxx.com/weather/get', // 替换为你的后端域名
        method: 'GET',
        data: {
          longitude,
          latitude
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.weather = res.data.data;
          } else {
            uni.showToast({
              title: '获取天气失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.loading = false;
        }
      });
    }
  }
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  text-align: center;
}

.loading {
  font-size: 18px;
  color: #888;
}

.weather-info {
  font-size: 24px;
  color: #333;
}

.location {
  font-weight: bold;
  margin-bottom: 10px;
}

.temperature {
  font-size: 36px;
  margin-bottom: 10px;
}

.description {
  font-size: 20px;
  margin-bottom: 10px;
}

.wind {
  font-size: 16px;
  color: #666;
}
</style>

四、运行流程

  1. 后端启动

    • 确保 ThinkPHP5 项目已部署到服务器,并可以通过 http://your-backend-domain/weather/get 访问接口。
    • 测试接口是否正常返回天气数据。
  2. 前端运行

    • 使用 HBuilderX 打开 UniApp 项目,运行到微信小程序或浏览器。
    • 页面加载时会自动获取用户位置,并调用后端接口获取天气数据。

五、注意事项

  1. 跨域问题
    如果前端和后端不在同一个域名下,需在后端启用 CORS 支持。在 application/middleware.php 中添加:

    use think\Middleware;
    
    Middleware::add(function ($request, $next) {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');
        return $next($request);
    });
  2. HTTPS 配置
    微信小程序要求所有接口必须使用 HTTPS,请确保后端已配置 SSL 证书。
  3. 高德 API 限制
    高德天气 API 免费版每日有调用次数限制(3000次),请根据实际需求选择合适的套餐。

六、总结

通过上述代码,我们实现了 UniApp 前端与 ThinkPHP5 后端结合高德天气 API 的完整天气预报功能。前端负责获取用户位置并调用后端接口,后端则负责调用高德 API 并返回天气数据。这种架构清晰分离了前后端职责,便于扩展和维护。

0 条评论

还没有人发表评论

发表评论 取消回复

记住我的信息,方便下次评论
有人回复时邮件通知我