fixphrase.com/lookup.php

66 lines
1.7 KiB
PHP
Raw Normal View History

2021-05-23 00:05:57 -06:00
<?php
require_once __DIR__ . "/FixPhrase.lib.php";
/**
* Build and send a simple JSON response.
* @param string $msg A message
* @param string $status "OK" or "ERROR"
* @param array $data More JSON data
*/
function sendJsonResp(string $msg = null, string $status = "OK", array $data = null) {
$resp = [];
if (!is_null($data)) {
$resp = $data;
}
if (!is_null($msg)) {
$resp["msg"] = $msg;
}
$resp["status"] = $status;
header("Content-Type: application/json");
exit(json_encode($resp));
}
function exitWithJson(array $json) {
header("Content-Type: application/json");
exit(json_encode($json));
}
$output = [];
try {
if (!empty($_GET["words"])) {
// convert words to coordinates
$words = urldecode($_GET["words"]);
$coords = FixPhrase::decode($words);
$output = [
"status" => "OK",
"action" => "decodeFromWords",
"words" => $words,
"coords" => $coords
];
} else if (!empty($_GET["latitude"]) && !empty($_GET["longitude"])) {
// convert coordinates to words
$lat = round($_GET["latitude"], 4);
$lon = round($_GET["longitude"], 4);
$words = FixPhrase::encode($lat, $lon);
$output = [
"status" => "OK",
"action" => "encodeToWords",
"words" => $words,
"coords" => [
$lat,
$lon
]
];
} else {
throw new Exception("Must supply either a string of words or a latitude/longitude pair.");
}
} catch (Exception $ex) {
sendJsonResp($ex->getMessage(), "ERROR");
}
exitWithJson($output);