4 * Description: Use the OpenCage Geocoder http://geocoder.opencagedata.com to resolve nearest populated location for given latitude, longitude. Derived from "geonames"
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Renderer;
14 function geocoordinates_install()
16 Hook::register('post_local', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
17 Hook::register('post_remote', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
20 function geocoordinates_resolve_item(&$item)
22 if((!$item["coord"]) || ($item["location"]))
25 $key = DI::config()->get("geocoordinates", "api_key");
29 $language = DI::config()->get("geocoordinates", "language");
33 $coords = explode(' ',$item["coord"]);
35 if (count($coords) < 2)
38 $coords[0] = round($coords[0], 5);
39 $coords[1] = round($coords[1], 5);
41 $result = DI::cache()->get("geocoordinates:".$language.":".$coords[0]."-".$coords[1]);
42 if (!is_null($result)) {
43 $item["location"] = $result;
47 $s = DI::httpClient()->fetch("https://api.opencagedata.com/geocode/v1/json?q=" . $coords[0] . "," . $coords[1] . "&key=" . $key . "&language=" . $language);
50 Logger::info("API could not be queried");
54 $data = json_decode($s);
56 if ($data->status->code != "200") {
57 Logger::info("API returned error ".$data->status->code." ".$data->status->message);
61 if (($data->total_results == 0) || (count($data->results) == 0)) {
62 Logger::info("No results found for coordinates ".$item["coord"]);
66 $item["location"] = $data->results[0]->formatted;
68 Logger::info("Got location for coordinates ".$coords[0]."-".$coords[1].": ".$item["location"]);
70 if ($item["location"] != "")
71 DI::cache()->set("geocoordinates:".$language.":".$coords[0]."-".$coords[1], $item["location"]);
74 function geocoordinates_post_hook($a, &$item)
76 geocoordinates_resolve_item($item);
79 function geocoordinates_addon_admin(&$a, &$o)
82 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/geocoordinates/");
84 $o = Renderer::replaceMacros($t, [
85 '$submit' => DI::l10n()->t('Save Settings'),
86 '$api_key' => ['api_key', DI::l10n()->t('API Key'), DI::config()->get('geocoordinates', 'api_key'), ''],
87 '$language' => ['language', DI::l10n()->t('Language code (IETF format)'), DI::config()->get('geocoordinates', 'language'), ''],
91 function geocoordinates_addon_admin_post(&$a)
93 $api_key = trim($_POST['api_key'] ?? '');
94 DI::config()->set('geocoordinates', 'api_key', $api_key);
96 $language = trim($_POST['language'] ?? '');
97 DI::config()->set('geocoordinates', 'language', $language);