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(array &$item)
23 if ((!$item['coord']) || ($item['location'])) {
27 $key = DI::config()->get('geocoordinates', 'api_key');
32 $language = DI::config()->get('geocoordinates', 'language');
33 if ($language == '') {
37 $coords = explode(' ', $item['coord']);
39 if (count($coords) < 2) {
43 $coords[0] = round($coords[0], 5);
44 $coords[1] = round($coords[1], 5);
46 $result = DI::cache()->get('geocoordinates:' . $language . ':' . $coords[0] . '-' . $coords[1]);
47 if (!is_null($result)) {
48 $item['location'] = $result;
52 $s = DI::httpClient()->fetch('https://api.opencagedata.com/geocode/v1/json?q=' . $coords[0] . ',' . $coords[1] . '&key=' . $key . '&language=' . $language);
55 Logger::info('API could not be queried');
59 $data = json_decode($s);
61 if ($data->status->code != '200') {
62 Logger::info('API returned error ' . $data->status->code . ' ' . $data->status->message);
66 if (($data->total_results == 0) || (count($data->results) == 0)) {
67 Logger::info('No results found for coordinates ' . $item['coord']);
71 $item['location'] = $data->results[0]->formatted;
73 Logger::info('Got location for coordinates ' . $coords[0] . '-' . $coords[1] . ': ' . $item['location']);
75 if ($item['location'] != '') {
76 DI::cache()->set('geocoordinates:' . $language.':' . $coords[0] . '-' . $coords[1], $item['location']);
80 function geocoordinates_post_hook(&$item)
82 geocoordinates_resolve_item($item);
85 function geocoordinates_addon_admin(string &$o)
87 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/geocoordinates/');
89 $o = Renderer::replaceMacros($t, [
90 '$submit' => DI::l10n()->t('Save Settings'),
91 '$api_key' => ['api_key', DI::l10n()->t('API Key'), DI::config()->get('geocoordinates', 'api_key'), ''],
92 '$language' => ['language', DI::l10n()->t('Language code (IETF format)'), DI::config()->get('geocoordinates', 'language'), ''],
96 function geocoordinates_addon_admin_post()
98 DI::config()->set('geocoordinates', 'api_key', trim($_POST['api_key'] ?? ''));
99 DI::config()->set('geocoordinates', 'language', trim($_POST['language'] ?? ''));