Defines default language and location for the geocoder in the configuration file.
[platal.git] / classes / gmapsgeocoder.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 // Implementation of a Geocoder using the Google Maps API. Please refer to
23 // the following links for details:
24 // http://code.google.com/apis/maps/documentation/services.html#Geocoding
25 // http://code.google.com/intl/en/apis/maps/documentation/geocoding/
26 // http://code.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
27 //
28 // It requires the properties gmaps_key and gmaps_url to be defined in section
29 // Geocoder in plat/al's configuration (platal.ini & platal.conf).
30 class GMapsGeocoder extends Geocoder {
31
32 // Maximum number of Geocoding calls to the Google Maps API.
33 const MAX_GMAPS_RPC_CALLS = 5;
34 // Maximum levenshtein distance authorized between input and geocoded text in a single line.
35 const MAX_LINE_DISTANCE = 5;
36 // Maximum levenshtein distance authorized between input and geocoded text in the whole text.
37 const MAX_TOTAL_DISTANCE = 6;
38
39 public function getGeocodedAddress(Address &$address) {
40 $this->prepareAddress($address);
41 $textAddress = $this->getTextToGeocode($address->text);
42
43 // Try to geocode the full address.
44 if (($geocodedData = $this->getPlacemarkForAddress($textAddress))) {
45 $this->getUpdatedAddress($address, $geocodedData, null);
46 return;
47 }
48
49 // If the full geocoding failed, try to geocode only the final part of the address.
50 // We start by geocoding everything but the first line, and continue until we get
51 // a result. To respect the limit of GMaps calls, we ignore the first few lines
52 // if there are too many address lines.
53 $addressLines = explode("\n", $textAddress);
54 $linesCount = count($addressLines);
55 for ($i = max(1, $linesCount - self::MAX_GMAPS_RPC_CALLS + 1); $i < $linesCount; ++$i) {
56 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
57 $toGeocode = implode("\n", array_slice($addressLines, $i));
58 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode))) {
59 $this->getUpdatedAddress($address, $geocodedData, $extraLines);
60 return;
61 }
62 }
63 }
64
65 public function stripGeocodingFromAddress(Address &$address) {
66 $address->geocodedText = null;
67 $address->geoloc_choice = null;
68 $address->countryId = null;
69 $address->country = null;
70 $address->administrativeAreaName = null;
71 $address->subAdministrativeAreaName = null;
72 $address->localityName = null;
73 $address->thoroughfareName = null;
74 $address->postalCode = null;
75 $address->accuracy = 0;
76 }
77
78 // Updates the address with the geocoded information from Google Maps. Also
79 // cleans up the final informations.
80 private function getUpdatedAddress(Address &$address, array $geocodedData, $extraLines) {
81 $this->fillAddressWithGeocoding($address, $geocodedData);
82 $this->formatAddress($address, $extraLines);
83 }
84
85 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
86 // address, by querying the Google Maps API. Returns the array on success,
87 // and null otherwise.
88 private function getPlacemarkForAddress($address) {
89 $url = $this->getGeocodingUrl($address);
90 $geoData = $this->getGeoJsonFromUrl($url);
91
92 return ($geoData ? $this->getPlacemarkFromJson($geoData) : null);
93 }
94
95 // Prepares address to be geocoded
96 private function prepareAddress(Address &$address) {
97 $address->text = preg_replace('/\s*\n\s*/m', "\n", trim($address->text));
98 }
99
100 // Builds the Google Maps geocoder url to fetch information about @p address.
101 // Returns the built url.
102 private function getGeocodingUrl($address) {
103 global $globals;
104
105 $parameters = array(
106 'key' => $globals->geocoder->gmaps_key,
107 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
108 'hl' => $globals->geocoder->gmaps_hl,
109 'oe' => 'utf8', // Output encoding.
110 'output' => 'json', // Output format.
111 'gl' => $globals->geocoder->gmaps_gl,
112 'q' => $address, // The queries address.
113 );
114
115 return $globals->geocoder->gmaps_url . '?' . http_build_query($parameters);
116 }
117
118 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
119 // Returns the json array on success, and null otherwise.
120 private function getGeoJsonFromUrl($url) {
121 global $globals;
122
123 // Prepare a backtrace object to log errors.
124 $bt = null;
125 if ($globals->debug & DEBUG_BT) {
126 if (!isset(PlBacktrace::$bt['Geoloc'])) {
127 new PlBacktrace('Geoloc');
128 }
129 $bt = &PlBacktrace::$bt['Geoloc'];
130 $bt->start($url);
131 }
132
133 // Fetch the geocoding data.
134 $rawData = file_get_contents($url);
135 if (!$rawData) {
136 if ($bt) {
137 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
138 }
139 return null;
140 }
141
142 // Decode the JSON-encoded data, and check for their validity.
143 $data = json_decode($rawData, true);
144 if ($bt) {
145 $bt->stop(count($data), null, $data);
146 }
147
148 return $data;
149 }
150
151 // Extracts the most appropriate placemark from the JSON data fetched from
152 // Google Maps. Returns a Placemark array on success, and null otherwise. See
153 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
154 // for details on the Placemark structure.
155 private function getPlacemarkFromJson(array $data) {
156 // Check for geocoding failures.
157 if (!isset($data['Status']['code']) || $data['Status']['code'] != 200) {
158 // TODO: handle non-200 codes in a better way, since the code might
159 // indicate a temporary error on Google's side.
160 return null;
161 }
162
163 // Check that at least one placemark was found.
164 if (count($data['Placemark']) == 0) {
165 return null;
166 }
167
168 // Extract the placemark with the best accuracy. This is not always the
169 // best result (since the same address may yield two different placemarks).
170 $result = $data['Placemark'][0];
171 foreach ($data['Placemark'] as $place) {
172 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
173 $result = $place;
174 }
175 }
176
177 return $result;
178 }
179
180 // Fills the address with the geocoded data
181 private function fillAddressWithGeocoding(Address &$address, $geocodedData) {
182 // The geocoded address three is
183 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
184 // with all the possible shortcuts
185 // The address is formatted as xAL, or eXtensible Address Language, an international
186 // standard for address formatting.
187 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
188 $address->geocodedText = str_replace(', ', "\n", $geocodedData['address']);
189 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
190 $address->accuracy = $geocodedData['AddressDetails']['Accuracy'];
191 }
192
193 $currentPosition = $geocodedData['AddressDetails'];
194 if (isset($currentPosition['Country'])) {
195 $currentPosition = $currentPosition['Country'];
196 $address->countryId = $currentPosition['CountryNameCode'];
197 $address->country = $currentPosition['CountryName'];
198 }
199 if (isset($currentPosition['AdministrativeArea'])) {
200 $currentPosition = $currentPosition['AdministrativeArea'];
201 $address->administrativeAreaName = $currentPosition['AdministrativeAreaName'];
202 }
203 if (isset($currentPosition['SubAdministrativeArea'])) {
204 $currentPosition = $currentPosition['SubAdministrativeArea'];
205 $address->subAdministrativeAreaName = $currentPosition['SubAdministrativeAreaName'];
206 }
207 if (isset($currentPosition['Locality'])) {
208 $currentPosition = $currentPosition['Locality'];
209 $address->localityName = $currentPosition['LocalityName'];
210 }
211 if (isset($currentPosition['Thoroughfare'])) {
212 $address->thoroughfareName = $currentPosition['Thoroughfare']['ThoroughfareName'];
213 }
214 if (isset($currentPosition['PostalCode'])) {
215 $address->postalCode = $currentPosition['PostalCode']['PostalCodeNumber'];
216 }
217
218 // Gets coordinates.
219 if (isset($geocodedData['Point']['coordinates'][0])) {
220 $address->latitude = $geocodedData['Point']['coordinates'][0];
221 }
222 if (isset($geocodedData['Point']['coordinates'][1])) {
223 $address->longitude = $geocodedData['Point']['coordinates'][1];
224 }
225 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
226 $address->north = $geocodedData['ExtendedData']['LatLonBox']['north'];
227 }
228 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
229 $address->south = $geocodedData['ExtendedData']['LatLonBox']['south'];
230 }
231 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
232 $address->east = $geocodedData['ExtendedData']['LatLonBox']['east'];
233 }
234 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
235 $address->west = $geocodedData['ExtendedData']['LatLonBox']['west'];
236 }
237 }
238
239 // Formats the text of the geocoded address using the unused data and
240 // compares it to the given address. If they are too different, the user
241 // will be asked to choose between them.
242 private function formatAddress(Address &$address, $extraLines) {
243 $same = true;
244 if ($extraLines) {
245 $address->geocodedText = $extraLines . "\n" . $address->geocodedText;
246 }
247 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
248 array('', "\n"), $address->geocodedText));
249 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
250 array('', "\n"), $address->text));
251 $arrayGeoloc = explode("\n", $geoloc);
252 $arrayText = explode("\n", $text);
253 $countGeoloc = count($arrayGeoloc);
254 $countText = count($arrayText);
255
256 $totalDistance = 0;
257 if (($countText > $countGeoloc) || ($countText < $countGeoloc - 1)
258 || (($countText == $countGeoloc - 1)
259 && ($arrayText[$countText - 1] == strtoupper($address->country)))) {
260 $same = false;
261 } else {
262 for ($i = 0; $i < $countGeoloc && $i < $countText; ++$i) {
263 $lineDistance = levenshtein($arrayText[$i], trim($arrayGeoloc[$i]));
264 $totalDistance += $lineDistance;
265 if ($lineDistance > self::MAX_LINE_DISTANCE || $totalDistance > self::MAX_TOTAL_DISTANCE) {
266 $same = false;
267 break;
268 }
269 }
270 }
271
272 if ($same) {
273 $address->geocodedText = null;
274 } else {
275 $address->geocodedText = str_replace("\n", "\r\n", $address->geocodedText);
276 }
277 $address->text = str_replace("\n", "\r\n", $address->text);
278 }
279
280 // Trims the name of the real country if it contains an ISO 3166-1 non-country
281 // item. For that purpose, we compare the last but one line of the address with
282 // all non-country items of ISO 3166-1.
283 private function getTextToGeocode($text)
284 {
285 $res = XDB::iterator('SELECT countryEn, country
286 FROM geoloc_countries
287 WHERE belongsTo IS NOT NULL');
288 $countries = array();
289 foreach ($res as $item) {
290 $countries[] = $item[0];
291 $countries[] = $item[1];
292 }
293 $textLines = explode("\n", $text);
294 $countLines = count($textLines);
295 $needle = strtoupper(trim($textLines[$countLines - 2]));
296 $isPseudoCountry = false;
297 foreach ($countries as $country) {
298 if (strtoupper($country) == $needle) {
299 $isPseudoCountry = true;
300 break;
301 }
302 }
303
304 if ($isPseudoCountry) {
305 return implode("\n", array_slice($textLines, 0, -1));
306 }
307 return $text;
308 }
309 }
310
311 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
312 ?>