Created
January 18, 2018 13:09
-
-
Save ckhung/c75bf4961fcbbbc06a67f0dc70df80f7 to your computer and use it in GitHub Desktop.
從 PTX (公共運輸整合資訊流通服務平台) 開放資料產生 geojson 檔
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?city=Taichung&rid=151 | |
# 其他城市名稱請見 http://ptx.transportdata.tw/ptx/Download/API_URI_Convention%E6%96%87%E4%BB%B6_v1.pdf 第 4 頁 | |
parse_str($_SERVER["QUERY_STRING"], $Q); | |
$time_string = gmdate('D, j M Y H:i:s') . ' GMT'; | |
$signature = base64_encode(hash_hmac("sha1", "x-date: $time_string", $_SERVER['PTX_KEY'], true)); | |
$opts = [ | |
"http" => [ | |
"method" => "GET", | |
"header" => | |
'Authorization:hmac username="' . $_SERVER['PTX_ID'] . '", algorithm="hmac-sha1", headers="x-date", signature="' . "$signature\"\n" . | |
"x-date:$time_string\n", | |
"Accept-Encoding: gzip, deflate\n", | |
] | |
]; | |
$ret = file_get_contents( | |
"http://ptx.transportdata.tw/MOTC/v2/Bus/RealTimeByFrequency/City/$Q[city]/$Q[rid]", false, stream_context_create($opts) | |
); | |
$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"], | |
] | |
] | |
]; | |
}, json_decode($ret, true) ); | |
$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 | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment