1: <?php
2: /**
3: * Geocode client for the Geonames API.
4: *
5: * Copyright 2009-2012 Horde LLC (http://www.horde.org/)
6: *
7: * See the enclosed file COPYING for license information (LGPL). If you
8: * did not receive this file, see http://www.horde.org/licenses/lgpl21.
9: *
10: * @author Michael J. Rubinsky <mrubinsk@horde.org>
11: * @category Horde
12: * @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
13: * @package Core
14: */
15: class Horde_Core_Ajax_Imple_Geocoder_Geonames extends Horde_Core_Ajax_Imple
16: {
17: /**
18: * Constructor.
19: *
20: * @param array $params Configuration parameters.
21: * <pre>
22: * 'triggerId' => (string) [optional] TODO
23: * </pre>
24: */
25: public function __construct($params)
26: {
27: parent::__construct($params);
28: }
29:
30: /**
31: * Attach the object to a javascript event.
32: */
33: public function attach()
34: {
35: }
36:
37: /**
38: * Handle the geocoding request.
39: *
40: * @TODO: For reverse requests come up with a reasonable algorithm for
41: * checking if we have a lat/lng in the US since the
42: * findNearestAddress method is US only. If non-us, fallback to a
43: * findNearest or findPostalcode or similar request. Also will need
44: * to normalize the various response structures.
45: *
46: * $args['locations'] will trigger a forward geocoding request.
47: * $args['lat'] and $args['lon'] will trigger a reverse geocoding request.
48: *
49: * @see Horde_Core_Ajax_Imple#handle($args, $post)
50: * @throws Horde_Exception
51: */
52: public function handle($args, $post)
53: {
54: if ($args['location']) {
55: $url = new Horde_Url('http://ws.geonames.org/searchJSON');
56: $url = $url->add('q', $args['location']);
57: } elseif (!empty($args['lat']) && !empty($args['lon'])) {
58: $url = new Horde_Url('http:/ws.geonames.org/findNearestJSON');
59: $url = $url->add(array('lat' => $args['lat'], 'lng' => $args['lon']));
60: }
61:
62: $client = $GLOBALS['injector']->getInstance('Horde_Core_Factory_HttpClient')->create();
63: try {
64: $response = $client->get($url);
65: } catch (Horde_Http_Exception $e) {
66: throw new Horde_Exception_Wrapped($e);
67: }
68:
69: return array(
70: 'results' => $response->getBody(),
71: 'status' => 200
72: );
73: }
74:
75: }
76: