Hiển thị các bài đăng có nhãn laravel. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn laravel. Hiển thị tất cả bài đăng

Thứ Ba, 25 tháng 1, 2022

Get Football ranking table with free API

 For sports fans it is common to follow the matches, update results, standings and player information. There are many websites, APIs that give us such data.

However, today I would like to introduce how to get the rankings, top football leagues by free api on apifootball.com, the results are shown below. Just get and display them on your website.

 

148-England-Premier-League

England-Premier-League (leagueId is 148)

 

We use Laravel with VueJS to do this.

1. Route:

The first is the route definition

// Route get rankings by tournament
Route::get(‘/standings/{leagueId}’, ‘Sport\FootballController@standings’);

// Route get team information in a tournament
Route::get(‘/teams/{leagueId}/{team_id}’, ‘Sport\FootballController@getTeams’);

// Route retrieves player details
Route::get(‘/players/{team_key}/{player_name}’, ‘Sport\FootballController@getPlayers’);

2. Controller

You need to register an API on the apifootball.com page, after having this API key, we use it to get data through the controller.

register-your-api-football

Your API

 

IDs of the tournaments (league_id), will be provided here: https://apifootball.com/coverage/

 

 

ids-of-the-tournaments

IDs of the tournaments (league_id)

 

The three functions in the controller have the following meanings:

– standings($leagueId): Ranking of a tournament.
– getTeams($league_id, $team_id): Team information in a tournament.
– getPlayers($team_key, $player_name): Details of players on the team.

 

In the FootballController file: App\Http\Controllers\Api\Sport

namespace App\Http\Controllers\Api\Sport;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FootballController extends Controller
{
private $api_key;

public function __construct($api_key = ‘YOUR_API_KEY’)
{
$this->api_key = $api_key;
}

public function standings($leagueId)
{
$APIkey = $this->api_key;
$curl_options = array(
CURLOPT_URL => “https://apiv2.apifootball.com/?action=get_standings&league_id=$leagueId&APIkey=$APIkey”,

CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 5
);

$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
$result = (array) json_decode($result);

return $result;
}

public function getTeams(Request $request, $league_id, $team_id)
{
// Because the code is quite long, I will put it in the download file at the bottom of the page
}

public function getPlayers(Request $request, $team_key, $player_name)
{
// Because the code is quite long, I will put it in the download file at the bottom of the page
}
}

 

3. VueJS

– In the app.js file: resource/js/app.js

require(‘./bootstrap’);

import Vue from ‘vue’;
import VueRouter from ‘vue-router’;

Vue.use(VueRouter);

import App from ‘./views/App’

// Fooball
import Standing from ‘./components/Football/StandingTable’;
import GetTeams from ‘./components/Football/GetTeams’;
import GetPlayers from ‘./components/Football/GetPlayers’;

const router = new VueRouter({
mode: ‘history’,
routes: [
{
path: ‘/’,
name: ‘home’,
component: Home
},
{
path: ‘/standings/:leagueId’,
name: ‘fb.standing’,
component: Standing
},
{
path: ‘/teams/:leagueId/:team_id’,
name: ‘fb.getTeams’,
component: GetTeams
},
{
path: ‘/players/:team_key/:player_name’,
name: ‘fb.getPlayers’,
component: GetPlayers
},

// …
],

});

const app = new Vue({
el: ‘#app’,
components: { App, Datepicker },
router,
});

– In the StandingTable.vue file: resource/js/components/Football/StandingTable.vue
// Because the code is quite long, I will put it in the download file at the bottom of the page

– In the GetTeams file: resource/js/components/Football/GetTeams.vue
// Because the code is quite long, I will put it in the download file at the bottom of the page

– In the GetPlayers file: resource/js/components/Football/GetPlayers.vue
// Because the code is quite long, I will put it in the download file at the bottom of the page

First I assume you pass leagueId = 148 (England – Premier League) which will be as shown above.

With leagueId = 468 (LaLiga), we will see the following.

 

468-LaLiga

LaLiga (leagueId id 468)

 

– Click View Detail to view detailed information.

 

barcenola-team-detail

Barcenola team detail

 

Reference links: https://popularinfo.net/standings/148

Wish you success with this free API, Laravel and VueJS thanks for reading the article.

 

Download full code: Download Size: 6 KB


Thứ Ba, 4 tháng 1, 2022

Add weather and time zone information to your website from free API

Today I will introduce to you how to get weather information and display it on your website, get information by available address or by your location.

We will be using a free account from https://home.openweathermap.org, you sign up with an email account and after confirming, you will receive the API from the incoming email. Of course you can create many APIs after logged in.

API key from the incoming email

 

Create API key name with name MyApiKey on home.openweathermap.org page

 

To display a select list of locations for information, you need latitude and longidute addresses. I assume you have list of coordinates of locations as below:

 

 

Note: Also you can refer to how to get the coordinates of other locations here Getting Latitude and Longitude from a Click Event

Once you have the information about the API key, the coordinates are needed. We proceed to get data combining Laravel and VueJS as follows:

Of course you only need to use Javascript is also completely applicable.

 

1. Routes

You create a file routes/api.php

Parameter lat, lng, timezone (purpose to get the current time of the selected coordinate).
Call the IndexController and index function.

Route::get(‘/weather/{lat}/{lng}/{timezone}’, ‘Weathers\IndexController@index’);

2. Controller

Next, you create a file Weathers\IndexController.php

We have List of pre-created time zones and APIKey, connect to API api.openweathermap.org/data/2.5/weather:

namespace App\Http\Controllers\Api\Weathers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{
/**
* Get Weather
*
* @param Request $request
* @param $lat
* @param $lng
* @param $timezone
* @return array
*/
public function index(Request $request, $lat, $lng, $timezone)
{
// By default, it is set GMT 0
date_default_timezone_set(‘UTC’); // default GMT 0

// List of pre-created time zones
$timezoneList = [
‘newyork’ => ‘America/New_York’,
‘tokyo’ => ‘Asia/Tokyo’,
‘shanghai’ => ‘Asia/Shanghai’,
‘london’ => ‘Europe/London’,
‘paris’ => ‘europe/paris’,
‘rome’ => ‘Europe/Rome’,
‘berlin’ => ‘europe/berlin’,
‘singapore’ => ‘asia/singapore’,
‘newdelhi’ => ‘Asia/Kolkata’,
‘bangkok’ => ‘asia/bangkok’,
‘seoul’ => ‘asia/seoul’,
];

if (!empty($timezone) && !empty($timezoneList[$timezone])) {
date_default_timezone_set($timezoneList[$timezone]);
}

// API is taken from openweathermap, you can put this API in ENV file
$APIKey = “YOUR_API_KEY”;
$curl_options = array(
CURLOPT_URL => “http://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lng&lang=en&units=metric&APPID=$APIKey”,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 5
);

$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );

$result = (array) json_decode($result);

// Get time information by selected location
$currentTime = time();
$weekTime = date(“l g:i a”, $currentTime);
$dmy = date(“jS F, Y”, $currentTime);

return [‘result’ => $result, ‘time’ => [‘weekTime’ => $weekTime, ‘dmy’ => $dmy]];
}
}

 

3. VueJS

Create a file assets/js/views/Home.vue

<template>
<div class=”col-lg-12 text-center”>
<div class=”text-left border-dash” v-if=”weatherResult”>
<div class=”row”>
<div class=”col-lg-2″>
<select class=”form-control select-location” @change=”onChange($event)” v-model=”key” style=”padding: 5px 0;margin: 0;height: auto;”>
<!– List of coordinates is taken first, with additional timezone parameter –>
<option value=”43.000351,-75.499901,newyork”>New York</option>
<option value=”39.916908,116.397057,shanghai”>Beijing</option>
<option value=”31.222219,121.458061,shanghai”>Shanghai</option>
<option value=”28.61282,77.23114,newdelhi”>New Delhi</option>
<option value=”35.689499,139.691711,tokyo”>Tokyo</option>
<option value=”37.583328,127.0,seoul”>Seoul</option>
<option value=”51.512791,-0.09184,london”>London</option>
<option value=”54.033329,10.45,berlin”>Berlin</option>
<option value=”48.853401,2.3486,paris”>Paris</option>
<option value=”41.894741,12.4839,rome”>Rome</option>
<option value=”1.28967,103.850067,singapore”>Singapore</option>
<option value=”13.87719,100.71991,bangkok”>Bangkok</option>
</select>
</div>

<!– Get weather, current time by location –>
<div class=”col-lg-10″>See weather, current time by location
<button v-on:click=”seeYourLocation” class=”btn btn-success” style=”text-transform: inherit;font-weight: normal;”>See weather your location</button>
</div>

<!– Show result –>
<div class=”col-lg-12″ v-if=”weatherResult”>
<b class=”w_name”>{{ weatherResult.name }}: </b>
<span v-if=”weatherTime” class=”w_time”>{{ weatherTime.weekTime }} – {{ weatherTime.dmy }}</span>

<span class=”w_des” v-if=”weatherResult.weather[0].description” style=”text-transform: capitalize;”>{{ weatherResult.weather[0].description }}. </span>

<img :src=”‘https://openweathermap.org/img/w/’ + weatherResult.weather[0].icon + ‘.png'” class=”w_icon” :alt=”Weather” v-if=”weatherResult.weather[0].icon”>
<span class=”w_temp_max” v-if=”weatherResult.main.temp_max”>Max: {{ weatherResult.main.temp_max }}&deg;C. </span>
<span class=”w_temp_min” v-if=”weatherResult.main.temp_min”>Min: {{ weatherResult.main.temp_min }}&deg;C. </span>

<span class=”w_humidity” v-if=”weatherResult.main.humidity”>Humidity: {{ weatherResult.main.humidity }} %. </span>
<span class=”w_wind” v-if=”weatherResult.wind.speed”>Wind: {{ weatherResult.wind.speed }} km/h.</span>
</div>
</div>
</div>
</div>
</template>
<script type=”text/javascript”>
// You can use axios to call the API, but in this article I will not use it
// import axios from ‘axios’;

export default {
data () {
return {
error: null,
weatherResult: ”, weatherTime: ”,
key: ‘43.000351,-75.499901,newyork’, lat: “43.000351”, lng: “-75.499901”, tzone: “newyork”, // The default setting is New York selected
};
},
created() {
// weather
this.weather();
},
methods: {
onChange(event) {
var latLng = event.target.value.split(‘,’);
var lat = latLng[0];
var lng = latLng[1];
var tzone = latLng[2];
this.lat = lat;
this.lng = lng;
this.tzone = tzone;

this.getWeather(this.lat, this.lng, this.tzone);
},

seeYourLocation: function (event) {
var lat = this.lat;
var lng = this.lng;
var tzone = ‘newyork’;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log(“Geolocation is not supported by this browser”);
}
}
function showPosition(position) {
// console.log(“position”, position);
// convert time from timestamp
// console.log(“this.position”, position);
var w_time = new Date(position.timestamp);
lat = position.coords.latitude;
lng = position.coords.longitude;

var api = “/api/weather/” + lat + “/” + lng + “/” + tzone;
axios
.get(api)
.then(response => {
// this.weatherResult = response.data.result;
// this.weatherTime = response.data.time;
var result = response.data.result;

$(‘.w_name’).text(result.name + ‘ : ‘);
$(‘.w_time’).text(w_time);
$(‘.w_temp_max’).text(‘Max: ‘ + result.main.temp_max + ‘°C. ‘);
$(‘.w_temp_min’).text(‘Min: ‘ + result.main.temp_min + ‘°C.’);
$(‘.w_humidity’).text(‘Humidity: ‘ + result.main.humidity + ‘%’);
$(‘.w_wind’).text(‘Wind: ‘ + result.wind.speed + ‘km/h.’);
$(‘.w_des’).text(result.weather[0].description);
$(“.w_icon”).attr(“src”, ‘https://openweathermap.org/img/w/’ + result.weather[0].icon + ‘.png’);

$(‘.select-location’).val(”);
}).catch(error => {
console.log(“error”, error);
});
}
getLocation();
},

weather() {
this.getWeather(this.lat, this.lng, this.tzone);
},

getWeather: function (lat, lng, tzone) {
var api = “/api/weather/” + lat + “/” + lng + “/” + tzone;
axios
.get(api)
.then(response => {
// console.log(“aaa”, response);
var result = response.data.result;
$(‘.w_name’).text(result.name + ‘ : ‘);
$(‘.w_time’).text(response.data.time.weekTime + ‘ – ‘ + response.data.time.dmy);
$(‘.w_temp_max’).text(‘Max: ‘ + result.main.temp_max + ‘°C. ‘);
$(‘.w_temp_min’).text(‘Min: ‘ + result.main.temp_min + ‘°C.’);
$(‘.w_humidity’).text(‘Humidity: ‘ + result.main.humidity + ‘%’);
$(‘.w_wind’).text(‘Wind: ‘ + result.wind.speed + ‘km/h.’);
$(‘.w_des’).text(result.weather[0].description);
$(“.w_icon”).attr(“src”, ‘https://openweathermap.org/img/w/’ + result.weather[0].icon + ‘.png’);

this.weatherResult = response.data.result;
this.weatherTime = response.data.time;

$(‘.select-location’).val(”);

}).catch(error => {
console.log(“error”, error);
});
}
}
}
</script>

 

4. Run webpack

Run watch to test

npm run watch

When you select a place from the list, the results will be displayed automatically. When you want to see information in your area, select [See weather your location] to get the results.

 

Weather information, time in New York

5. Conclusion

In the above simple example we have got the weather, temperature, time information of the selected coordinates, you can simply javascript and html to get the result like above.

 

Thanks for reading the article.