Created
September 21, 2023 11:43
-
-
Save ckhung/b4671eb7180a0688b4769a22ba8be282 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# 範例參數: | |
# bus-pos.php?line=Taichung/151 | |
# 其他城市名稱請見 | |
$QS = array_key_exists('QUERY_STRING', $_SERVER) ? $_SERVER["QUERY_STRING"] : ''; | |
parse_str($QS, $Q); | |
# $Q = array( | |
# 'line' => 'Taichung/151' | |
# ); | |
# https://github.com/tdxmotc/SampleCode | |
$TDX_TOKEN_DIR = "/home/ckhung/cred/tdx"; | |
$token = json_decode(file_get_contents("$TDX_TOKEN_DIR/tdx-credential.json"), true)['access_token']; | |
$opts = [ | |
'http' => [ | |
'method' => 'GET', | |
'header' => "authorization: Bearer $token" | |
] | |
]; | |
$ret = json_decode(file_get_contents( | |
"https://tdx.transportdata.tw/api/basic/v2/Bus/RealTimeByFrequency/City/$Q[line]?\$format=JSON", false, stream_context_create($opts) | |
), true); | |
$ret = array_map( function($v) { | |
return [ | |
"type" => "Feature", | |
"properties" => [ | |
"name" => $v["PlateNumb"], | |
"Azimuth" => $v["Azimuth"], | |
], | |
"geometry" => [ | |
"type" => "Point", | |
"coordinates" => [ | |
$v["BusPosition"]["PositionLon"], | |
$v["BusPosition"]["PositionLat"], | |
] | |
] | |
]; | |
}, $ret); | |
$ret = json_encode([ | |
"type" => "FeatureCollection", | |
"features" => $ret | |
]); | |
# firefox 認得 json | |
# https://developer.mozilla.org/en-US/docs/Tools/JSON_viewer | |
# 但不認得 geojson | |
# header('Content-Type: application/vnd.geo+json'); | |
header('Content-Type: application/json'); | |
print $ret; | |
# 另外 apache2 可能還需要設定 CORS: | |
# 在 /etc/apache2/sites-available/000-default.conf 裡面加入 | |
# Header set Access-Control-Allow-Origin "*" | |
# a2enmod headers | |
# systemctl restart apache2.service | |
?> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
export TDX_TOKEN_DIR=$HOME/.cache/tdx/ | |
mkdir -p $TDX_TOKEN_DIR | |
env > $TDX_TOKEN_DIR/env.txt | |
curl --request POST \ | |
--url 'https://tdx.transportdata.tw/auth/realms/TDXConnect/protocol/openid-connect/token' \ | |
--header content-type:application/x-www-form-urlencoded \ | |
--data grant_type=client_credentials \ | |
--data client_id=xxxxxx-xxxxxxxx-xxxx-xxxx \ | |
--data client_secret=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \ | |
> $TDX_TOKEN_DIR/tdx-credential.json | |
export TDX_ACCESS_TOKEN=$(jq .access_token $TDX_TOKEN_DIR/tdx-credential.json | sed 's/"//g') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment