fixphrase.com/lookup.php

81 lines
2.2 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"]);
2021-10-20 00:32:46 -06:00
$words = trim(strtolower($words));
$words = preg_replace('/\s+/', ' ', $words);
2021-05-23 00:05:57 -06:00
$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 if (!empty($_GET["search"])) {
$resp = file_get_contents("https://data.netsyms.net/v1/gis/geocode/?address=" . urlencode($_GET["search"]));
$data = json_decode($resp, true);
if ($data["status"] == "OK") {
$output = [
"status" => "OK",
"action" => "geocode",
"coords" => $data["coords"]
];
} else {
throw new Exception($data["message"]);
}
2021-05-23 00:05:57 -06:00
} else {
throw new Exception("Must supply either a string of words, a latitude/longitude pair, or a search query.");
2021-05-23 00:05:57 -06:00
}
} catch (Exception $ex) {
sendJsonResp($ex->getMessage(), "ERROR");
}
exitWithJson($output);