Skip to content

Instantly share code, notes, and snippets.

@mingtsay
Created February 12, 2018 13:08
Show Gist options
  • Save mingtsay/44a10d420748441dd1b63ea01ec4b228 to your computer and use it in GitHub Desktop.
Save mingtsay/44a10d420748441dd1b63ea01ec4b228 to your computer and use it in GitHub Desktop.
<?php
$cities = [
'Taipei',
'NewTaipei',
'Taoyuan',
'Taichung',
'Tainan',
'Kaoshiung',
'KinmenCountry',
'TaipeiCloud',
];
$parameters = [
'select',
'filter',
'orderby',
'top',
'skip',
];
$apiUrlPrefix = 'http://ptx.transportdata.tw/MOTC/v2/Bus/Shape/City/';
$city = $_GET['city'] ?? '';
if (!in_array($city, $cities))
$city = $cities[0];
$apiUrl = $apiUrlPrefix . $city. '?$format=json';
foreach ($parameters as $parameter)
if (isset($_GET[$parameter]))
$apiUrl .= '&$' . $parameter . '=' . urlencode($_GET[$parameter]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (RM Studio)');
ob_start();
curl_exec($ch);
$raw = ob_get_contents();
ob_end_clean();
curl_close($ch);
$data = json_decode($raw, true);
$geojson = [
'type' => 'FeatureCollection',
'features' => [],
];
foreach ($data as $route) {
$feature = [
'type' => 'Feature',
'properties' => [],
'geometry' => [
'type' => 'LineString',
'coordinates' => [],
],
];
foreach ($route as $key => $value) {
if ($key == 'Geometry') {
$coor = explode(', ', substr($value, 12, -1));
foreach ($coor as &$c) {
$c = explode(' ', $c);
$c[0] = (double)$c[0];
$c[1] = (double)$c[1];
}
$feature['geometry']['coordinates'] = $coor;
continue;
}
$feature['properties'][$key] = $value;
}
$geojson['features'][] = $feature;
}
echo(json_encode($geojson));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment