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 function geocoordinates_install() {
10 register_hook('post_local', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
11 register_hook('post_remote', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
15 function geocoordinates_uninstall() {
16 unregister_hook('post_local', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
17 unregister_hook('post_remote', 'addon/geocoordinates/geocoordinates.php', 'geocoordinates_post_hook');
20 function geocoordinates_resolve_item(&$item) {
21 if((!$item["coord"]) || ($item["location"]))
24 $key = get_config("geocoordinates", "api_key");
28 $language = get_config("geocoordinates", "language");
32 $coords = explode(' ',$item["coord"]);
34 if (count($coords) < 2)
37 $coords[0] = round($coords[0], 5);
38 $coords[1] = round($coords[1], 5);
40 $result = Cache::get("geocoordinates:".$language.":".$coords[0]."-".$coords[1]);
41 if (!is_null($result)) {
42 $item["location"] = $result;
46 $s = fetch_url("https://api.opencagedata.com/geocode/v1/json?q=".$coords[0].",".$coords[1]."&key=".$key."&language=".$language);
49 logger("API could not be queried", LOGGER_DEBUG);
53 $data = json_decode($s);
55 if ($data->status->code != "200") {
56 logger("API returned error ".$data->status->code." ".$data->status->message, LOGGER_DEBUG);
60 if (($data->total_results == 0) OR (count($data->results) == 0)) {
61 logger("No results found for coordinates ".$item["coord"], LOGGER_DEBUG);
65 $item["location"] = $data->results[0]->formatted;
67 logger("Got location for coordinates ".$coords[0]."-".$coords[1].": ".$item["location"], LOGGER_DEBUG);
69 if ($item["location"] != "")
70 Cache::set("geocoordinates:".$language.":".$coords[0]."-".$coords[1], $item["location"]);
73 function geocoordinates_post_hook($a, &$item) {
74 geocoordinates_resolve_item($item);
77 function geocoordinates_plugin_admin(&$a,&$o) {
79 $t = get_markup_template("admin.tpl", "addon/geocoordinates/");
81 $o = replace_macros($t, array(
82 '$submit' => t('Save Settings'),
83 '$api_key' => array('api_key', t('API Key'), get_config('geocoordinates', 'api_key' ), ''),
84 '$language' => array('language', t('Language code (IETF format)'), get_config('geocoordinates', 'language' ), ''),
88 function geocoordinates_plugin_admin_post(&$a) {
89 $api_key = ((x($_POST,'api_key')) ? notags(trim($_POST['api_key'])) : '');
90 set_config('geocoordinates','api_key',$api_key);
92 $language = ((x($_POST,'language')) ? notags(trim($_POST['language'])) : '');
93 set_config('geocoordinates','language',$language);
94 info(t('Settings updated.'). EOL);