andyjh07/weather

一个简单的Laravel天气api.com包

0.1.0 2021-07-14 00:46 UTC

This package is not auto-updated.

Last update: 2024-10-03 14:19:20 UTC


README

这是一个超级简单的包,可以根据IP地址返回未来3天的天气预报(付费计划可以查看更多天数)。此包基于来自https://www.weatherapi.com/的免费API。

安装

首先,通过Composer安装此包

composer require andyjh07/weather

完成之后,运行以下命令

php artisan weather:install

这将发布配置文件,以便您可以直接修改,或者简单地使用下面的env变量。

在这个阶段需要做的最后一件事是确保您运行了结果表的迁移

php artisan migrate

环境变量

为了正确运行此包,您需要将以下环境变量添加到您的.env文件中

WEATHER_API_KEY - 来自weatherapi.com的API密钥

WEATHER_FORMAT - 默认设置为JSON,但也可以使用XML。

WEATHER_CACHE_SECONDS - 默认为60。

WEATHER_DAYS - 默认为3。

用法/示例

设置所有环境变量后,您就可以开始显示所需的数据了。如果您只想快速尝试一下,可以尝试以下命令。它使用JSON数据集,所以如果将您的WEATHER_FORMAT设置为XML,则此处不会使用。

php artisan weather:get {ip}

请确保将IP地址传递给命令作为参数

php artisan weather:get 8.8.8.8

完整实现

到现在,您可能想开始在您的应用程序中使用此包,以下是使用JSON实现快速启动的方法。

更新web.php路由文件

打开web.php并修改/路由声明为以下内容

Route::get('/', function () {
    $weather = Weather::getWeatherRaw()->andReturn();

    return view('welcome', [
        'weather' => json_decode($weather)
    ]);
});

这将加载默认IP地址的天气数据。假设您现在想使用自己的IP地址,所以只需像下面这样传递参数即可(我将使用8.8.8.8作为示例)

$weather = Weather::getWeatherRaw("8.8.8.8")->andReturn();

保存结果(可选)

如果您希望在调用API时保存结果,可以在初始的getWeatherRaw()方法之后链式调用save()方法,如下所示

$weather = Weather::getWeatherRaw("8.8.8.8")->save()->andReturn();

这将获取天气数据,将其保存到Results表,然后像之前一样返回数据到视图。

NB - 此功能仍需要一些调整。

显示结果

下面的示例代码块使用Tailwind进行样式设置,所以为了使事物看起来更好,让我们添加CDN文件。打开welcome.blade.php并在</head>行上方添加以下行。

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">

如果您遇到样式问题,可能需要删除<style>...</style>标签内的内联样式。

接下来,您想添加一个循环遍历结果的代码块。我将它放在具有max-w-6xl mx-auto类的第二个div的末尾。

<h1 class="text-black text-3xl mt-8 font-bold text-center lg:text-left">{{ count($weather->forecast->forecastday)}} day forecast for {{ $weather->location->name }}, {{ $weather->location->country }}.</h1>
<div class="flex mx-auto flex-col w-2/3 lg:w-full lg:flex-row justify-center lg:justify-between mt-4 text-black">
    @foreach($weather->forecast->forecastday as $forecast)
    <div class="flex justify-center items-center lg:items-end p-4 lg:p-0 px-4">
        <div class="flex w-full items-center lg:items-end">
            <div class="flex flex-col w-1/2">
                <p class="font-bold">{{ \Carbon\Carbon::parse($forecast->date)->format('jS F Y') }}</p>
                <small>{{ $forecast->day->condition->text }}</small>
            </div>
            <div class="flex flex-col w-1/2">
                <small>Max Temp: {{ $forecast->day->maxtemp_c }}&deg;C</small>
                <small class="text-xs">Average Temp: {{ $forecast->day->avgtemp_c }}&deg;C</small>
            </div>
        </div>
        <img class="w-1/6" src="{{ $forecast->day->condition->icon }}" alt="{{ $forecast->day->condition->text }} icon">
    </div>
    @endforeach
</div>

您会注意到上面的示例使用Carbon内联格式化API返回的日期。

希望,如果一切顺利,您应该会看到类似下面的截图

Screenshot