2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
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
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
{
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;
39 public function getGeocodedAddress(Address
$address, $defaultLanguage = null
, $forceLanguage = false
) {
40 $this->prepareAddress($address);
41 $textAddress = $this->getTextToGeocode($address->text
);
42 if (is_null($defaultLanguage)) {
43 $defaultLanguage = Platal
::globals()->geocoder
->gmaps_hl
;
46 // Try to geocode the full address.
47 if (($geocodedData = $this->getPlacemarkForAddress($textAddress, $defaultLanguage))) {
48 $this->getUpdatedAddress($address, $geocodedData, null
, $forceLanguage);
52 // If the full geocoding failed, try to geocode only the final part of the address.
53 // We start by geocoding everything but the first line, and continue until we get
54 // a result. To respect the limit of GMaps calls, we ignore the first few lines
55 // if there are too many address lines.
56 $addressLines = explode("\n", $textAddress);
57 $linesCount = count($addressLines);
58 for ($i = max(1, $linesCount - self
::MAX_GMAPS_RPC_CALLS +
1); $i < $linesCount; ++
$i) {
59 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
60 $toGeocode = implode("\n", array_slice($addressLines, $i));
61 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode, $defaultLanguage))) {
62 $this->getUpdatedAddress($address, $geocodedData, $extraLines, $forceLanguage);
68 public function stripGeocodingFromAddress(Address
$address) {
69 $address->geocodedText
= null
;
70 $address->geoloc_choice
= null
;
71 $address->countryId
= null
;
72 $address->country
= null
;
73 $address->administrativeAreaName
= null
;
74 $address->subAdministrativeAreaName
= null
;
75 $address->localityName
= null
;
76 $address->thoroughfareName
= null
;
77 $address->postalCode
= null
;
78 $address->accuracy
= 0;
81 // Updates the address with the geocoded information from Google Maps. Also
82 // cleans up the final informations.
83 private function getUpdatedAddress(Address
$address, array $geocodedData, $extraLines, $forceLanguage) {
84 $this->fillAddressWithGeocoding($address, $geocodedData, false
);
85 $this->formatAddress($address, $extraLines, $forceLanguage);
88 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
89 // address, by querying the Google Maps API. Returns the array on success,
90 // and null otherwise.
91 private function getPlacemarkForAddress($address, $defaultLanguage) {
92 $url = $this->getGeocodingUrl($address, $defaultLanguage);
93 $geoData = $this->getGeoJsonFromUrl($url);
95 return ($geoData ?
$this->getPlacemarkFromJson($geoData) : null
);
98 // Prepares address to be geocoded
99 private function prepareAddress(Address
$address) {
100 $address->text
= preg_replace('/\s*\n\s*/m', "\n", trim($address->text
));
103 // Builds the Google Maps geocoder url to fetch information about @p address.
104 // Returns the built url.
105 private function getGeocodingUrl($address, $defaultLanguage) {
109 'key' => $globals->geocoder
->gmaps_key
,
110 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
111 'hl' => $defaultLanguage,
112 'oe' => 'utf8', // Output encoding.
113 'output' => 'json', // Output format.
114 'gl' => $globals->geocoder
->gmaps_gl
,
115 'q' => $address, // The queries address.
118 return $globals->geocoder
->gmaps_url
. '?' . http_build_query($parameters);
121 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
122 // Returns the json array on success, and null otherwise.
123 private function getGeoJsonFromUrl($url) {
126 // Prepare a backtrace object to log errors.
128 if ($globals->debug
& DEBUG_BT
) {
129 if (!isset(PlBacktrace
::$bt['Geoloc'])) {
130 new PlBacktrace('Geoloc');
132 $bt = &PlBacktrace
::$bt['Geoloc'];
136 // Fetch the geocoding data.
137 $rawData = file_get_contents($url);
140 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
145 // Decode the JSON-encoded data, and check for their validity.
146 $data = json_decode($rawData, true
);
148 $bt->stop(count($data), null
, $data);
154 // Extracts the most appropriate placemark from the JSON data fetched from
155 // Google Maps. Returns a Placemark array on success, and null otherwise. See
156 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
157 // for details on the Placemark structure.
158 private function getPlacemarkFromJson(array $data) {
159 // Check for geocoding failures.
160 if (!isset($data['Status']['code']) ||
$data['Status']['code'] != 200) {
161 // TODO: handle non-200 codes in a better way, since the code might
162 // indicate a temporary error on Google's side.
166 // Check that at least one placemark was found.
167 if (count($data['Placemark']) == 0) {
171 // Extract the placemark with the best accuracy. This is not always the
172 // best result (since the same address may yield two different placemarks).
173 $result = $data['Placemark'][0];
174 foreach ($data['Placemark'] as $place) {
175 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
183 // Fills the address with the geocoded data
184 private function fillAddressWithGeocoding(Address
$address, $geocodedData, $isLocal) {
185 // The geocoded address three is
186 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
187 // with all the possible shortcuts
188 // The address is formatted as xAL, or eXtensible Address Language, an international
189 // standard for address formatting.
190 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
194 $ext = ucfirst(Platal
::globals()->geocoder
->gmaps_hl
);
195 $address->geocodedText
= str_replace(', ', "\n", $geocodedData['address']);
198 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
199 $address->accuracy
= $geocodedData['AddressDetails']['Accuracy'];
202 $currentPosition = $geocodedData['AddressDetails'];
203 if (isset($currentPosition['Country'])) {
204 $country = 'country' . $ext;
205 $currentPosition = $currentPosition['Country'];
206 $address->countryId
= $currentPosition['CountryNameCode'];
207 $address->$country = $currentPosition['CountryName'];
209 if (isset($currentPosition['AdministrativeArea'])) {
210 $administrativeAreaName = 'administrativeAreaName' . $ext;
211 $currentPosition = $currentPosition['AdministrativeArea'];
212 $address->$administrativeAreaName = $currentPosition['AdministrativeAreaName'];
214 if (isset($currentPosition['SubAdministrativeArea'])) {
215 $subAdministrativeAreaName = 'subAdministrativeAreaName' . $ext;
216 $currentPosition = $currentPosition['SubAdministrativeArea'];
217 $address->$subAdministrativeAreaName = $currentPosition['SubAdministrativeAreaName'];
219 if (isset($currentPosition['Locality'])) {
220 $localityName = 'localityName' . $ext;
221 $currentPosition = $currentPosition['Locality'];
222 $address->$localityName = $currentPosition['LocalityName'];
224 if (isset($currentPosition['PostalCode'])) {
225 $address->postalCode
= $currentPosition['PostalCode']['PostalCodeNumber'];
229 if (isset($geocodedData['Point']['coordinates'][0])) {
230 $address->latitude
= $geocodedData['Point']['coordinates'][0];
232 if (isset($geocodedData['Point']['coordinates'][1])) {
233 $address->longitude
= $geocodedData['Point']['coordinates'][1];
235 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
236 $address->north
= $geocodedData['ExtendedData']['LatLonBox']['north'];
238 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
239 $address->south
= $geocodedData['ExtendedData']['LatLonBox']['south'];
241 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
242 $address->east
= $geocodedData['ExtendedData']['LatLonBox']['east'];
244 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
245 $address->west
= $geocodedData['ExtendedData']['LatLonBox']['west'];
249 // Compares the geocoded address with the given address and returns true
250 // iff their are close enough to be considered as equals or not.
251 private function compareAddress($address)
254 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
255 array('', "\n"), $address->geocodedText
));
256 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
257 array('', "\n"), $address->text
));
258 $arrayGeoloc = explode("\n", $geoloc);
259 $arrayText = explode("\n", $text);
260 $countGeoloc = count($arrayGeoloc);
261 $countText = count($arrayText);
264 if (($countText > $countGeoloc) ||
($countText < $countGeoloc - 1)
265 ||
(($countText == $countGeoloc - 1)
266 && ($arrayText[$countText - 1] == strtoupper($address->country
)))) {
269 for ($i = 0; $i < $countGeoloc && $i < $countText; ++
$i) {
270 $lineDistance = levenshtein($arrayText[$i], trim($arrayGeoloc[$i]));
271 $totalDistance +
= $lineDistance;
272 if ($lineDistance > self
::MAX_LINE_DISTANCE ||
$totalDistance > self
::MAX_TOTAL_DISTANCE
) {
282 // Formats the text of the geocoded address using the unused data and
283 // compares it to the given address. If they are too different, the user
284 // will be asked to choose between them.
285 private function formatAddress(Address
$address, $extraLines, $forceLanguage)
288 $address->geocodedText
= $extraLines . "\n" . $address->geocodedText
;
291 if ($this->compareAddress($address)) {
292 $address->geocodedText
= null
;
293 } elseif (!$forceLanguage) {
294 $languages = XDB
::fetchOneCell('SELECT IF(ISNULL(gc1.belongsTo), gl1.language, gl2.language)
295 FROM geoloc_countries AS gc1
296 INNER JOIN geoloc_languages AS gl1 ON (gc1.iso_3166_1_a2 = gl1.iso_3166_1_a2)
297 LEFT JOIN geoloc_countries AS gc2 ON (gc1.belongsTo = gc2.iso_3166_1_a2)
298 LEFT JOIN geoloc_languages AS gl2 ON (gc2.iso_3166_1_a2 = gl2.iso_3166_1_a2)
299 WHERE gc1.iso_3166_1_a2 = {?}',
300 $address->countryId
);
301 $toGeocode = substr($address->text
, strlen($extraLines));
302 foreach (explode(',', $languages) as $language) {
303 if ($language != Platal
::globals()->geocoder
->gmaps_hl
) {
304 $geocodedData = $this->getPlacemarkForAddress($toGeocode, $language);
305 $address->geocodedText
= str_replace(', ', "\n", $geocodedData['address']);
307 $address->geocodedText
= $extraLines . "\n" . $address->geocodedText
;
309 if ($this->compareAddress($address)) {
310 $this->fillAddressWithGeocoding($address, $geocodedData, true
);
311 $address->geocodedText
= null
;
316 $address->geocodedText
= str_replace("\n", "\r\n", $address->geocodedText
);
318 $address->text
= str_replace("\n", "\r\n", $address->text
);
321 // Trims the name of the real country if it contains an ISO 3166-1 non-country
322 // item. For that purpose, we compare the last but one line of the address with
323 // all non-country items of ISO 3166-1.
324 private function getTextToGeocode($text)
326 $res = XDB
::iterator('SELECT countryEn, country
327 FROM geoloc_countries
328 WHERE belongsTo IS NOT NULL');
329 $countries = array();
330 foreach ($res as $item) {
331 $countries[] = $item[0];
332 $countries[] = $item[1];
334 $textLines = explode("\n", $text);
335 $countLines = count($textLines);
336 $needle = strtoupper(trim($textLines[$countLines - 2]));
337 $isPseudoCountry = false
;
339 foreach ($countries as $country) {
340 if (strtoupper($country) === $needle) {
341 $isPseudoCountry = true
;
347 if ($isPseudoCountry) {
348 return implode("\n", array_slice($textLines, 0, -1));
354 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: