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>
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Renderer;
15 function geocoordinates_install()
17 Hook::register('post_local', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
18 Hook::register('post_remote', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
21 function geocoordinates_resolve_item(&$item)
23 if((!$item["coord"]) || ($item["location"]))
26 $key = DI::config()->get("geocoordinates", "api_key");
30 $language = DI::config()->get("geocoordinates", "language");
34 $coords = explode(' ',$item["coord"]);
36 if (count($coords) < 2)
39 $coords[0] = round($coords[0], 5);
40 $coords[1] = round($coords[1], 5);
42 $result = DI::cache()->get("geocoordinates:".$language.":".$coords[0]."-".$coords[1]);
43 if (!is_null($result)) {
44 $item["location"] = $result;
48 $s = DI::httpClient()->fetch("https://api.opencagedata.com/geocode/v1/json?q=" . $coords[0] . "," . $coords[1] . "&key=" . $key . "&language=" . $language);
51 Logger::info("API could not be queried");
55 $data = json_decode($s);
57 if ($data->status->code != "200") {
58 Logger::info("API returned error ".$data->status->code." ".$data->status->message);
62 if (($data->total_results == 0) || (count($data->results) == 0)) {
63 Logger::info("No results found for coordinates ".$item["coord"]);
67 $item["location"] = $data->results[0]->formatted;
69 Logger::info("Got location for coordinates ".$coords[0]."-".$coords[1].": ".$item["location"]);
71 if ($item["location"] != "")
72 DI::cache()->set("geocoordinates:".$language.":".$coords[0]."-".$coords[1], $item["location"]);
75 function geocoordinates_post_hook(App $a, &$item)
77 geocoordinates_resolve_item($item);
80 function geocoordinates_addon_admin(App $a, &$o)
83 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/geocoordinates/");
85 $o = Renderer::replaceMacros($t, [
86 '$submit' => DI::l10n()->t('Save Settings'),
87 '$api_key' => ['api_key', DI::l10n()->t('API Key'), DI::config()->get('geocoordinates', 'api_key'), ''],
88 '$language' => ['language', DI::l10n()->t('Language code (IETF format)'), DI::config()->get('geocoordinates', 'language'), ''],
92 function geocoordinates_addon_admin_post(App $a)
94 $api_key = trim($_POST['api_key'] ?? '');
95 DI::config()->set('geocoordinates', 'api_key', $api_key);
97 $language = trim($_POST['language'] ?? '');
98 DI::config()->set('geocoordinates', 'language', $language);