9538faa7d11f783c211ea46a734a74c50f6de79f
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 // Interface for an address geocoder. It provides support for transforming a free
23 // form address into a fully structured one.
24 // TODO: define and use an Address object instead of a key-value map.
25 abstract class Geocoder
{
26 // Geocodes @p the address, and returns the corresponding updated address.
27 // Unknown key-value pairs available in the input map are retained as-is.
28 abstract public function getGeocodedAddress(array $address);
30 // Updates geoloc_administrativeareas, geoloc_subadministrativeareas and
31 // geoloc_localities databases with new geocoded data and returns the
33 static public function getAreaId(array &$address, $area)
35 static $databases = array(
36 'administrativeArea' => 'geoloc_administrativeareas',
37 'subAdministrativeArea' => 'geoloc_subadministrativeareas',
38 'locality' => 'geoloc_localities',
41 if (isset($address[$area . 'Name']) && isset($databases[$area])) {
42 $res = XDB
::query("SELECT id
43 FROM " . $databases[$area] . "
45 $address[$area . 'Name']);
46 if ($res->numRows() == 0) {
47 $address[$area . 'Id'] = XDB
::execute("INSERT INTO " . $databases[$area] . " (name, country)
49 $address[$area . 'Name'], $address['countryId']);
51 $address[$area . 'Id'] = $res->fetchOneCell();
56 // Returns the part of the text preceeding the line with the postal code
57 // and the city name, within the limit of $limit number of lines.
58 static public function getFirstLines($text, $postalCode, $limit)
60 $textArray = explode("\n", $text);
61 for ($i = 0; $i < count($textArray); ++
$i) {
62 if ($i > $limit ||
strpos($textLine, $postalCode) !== false
) {
66 return implode("\n", array_slice($textArray, 0, $limit));
70 // Implementation of a Geocoder using the Google Maps API. Please refer to
71 // the following links for details:
72 // http://code.google.com/apis/maps/documentation/services.html#Geocoding
73 // http://code.google.com/intl/en/apis/maps/documentation/geocoding/
74 // http://code.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
76 // It requires the properties gmaps_key and gmaps_url to be defined in section
77 // Geocoder in plat/al's configuration (platal.ini & platal.conf).
78 class GMapsGeocoder
extends Geocoder
{
80 // Maximum number of Geocoding calls to the Google Maps API.
81 const MAX_GMAPS_RPC_CALLS
= 5;
83 public function getGeocodedAddress(array $address) {
84 $address = $this->prepareAddress($address);
85 $textAddress = $address['text'];
87 // Try to geocode the full address.
88 if (($geocodedData = $this->getPlacemarkForAddress($textAddress))) {
89 return $this->getUpdatedAddress($address, $geocodedData, null
);
92 // If the full geocoding failed, try to geocode only the final part of the address.
93 // We start by geocoding everything but the first line, and continue until we get
94 // a result. To respect the limit of GMaps calls, we ignore the first few lines
95 // if there are too many address lines.
96 $addressLines = explode("\n", $textAddress);
97 $linesCount = count($addressLines);
98 for ($i = max(1, $linesCount - self
::MAX_GMAPS_RPC_CALLS +
1); $i < $linesCount; ++
$i) {
99 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
100 $toGeocode = implode("\n", array_slice($addressLines, $i));
101 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode))) {
102 return $this->getUpdatedAddress($address, $geocodedData, $extraLines);
106 // No geocoding could be done, the initial address is returned as-is.
110 // Updates the address with the geocoded information from Google Maps. Also
111 // cleans up the final informations.
112 private function getUpdatedAddress(array $address, array $geocodedData, $extraLines) {
113 $this->fillAddressWithGeocoding(&$address, $geocodedData);
115 // If the accuracy is 6, it means only the street has been gecoded
116 // but not the number, thus we need to fix it.
117 if ($address['accuracy'] == 6) {
118 $this->fixStreetNumber($address);
121 // We can now format the address.
122 $this->formatAddress($address, $extraLines);
124 // Some entities in ISO 3166 are not countries, thus they have to be replaced
125 // by the country they belong to.
126 // TODO: fixCountry($address);
131 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
132 // address, by querying the Google Maps API. Returns the array on success,
133 // and null otherwise.
134 private function getPlacemarkForAddress($address) {
135 $url = $this->getGeocodingUrl($address);
136 $geoData = $this->getGeoJsonFromUrl($url);
138 return ($geoData ?
$this->getPlacemarkFromJson($geoData) : null
);
141 // Prepares address to be geocoded
142 private function prepareAddress($address) {
143 $address['text'] = preg_replace('/\s*\n\s*/m', "\n", trim($address['text']));
144 // TODO: $address['postalAddress'] = getPostalAddress($address['text']);
145 $address['updateTime'] = time();
146 unset($address['changed']);
150 // Builds the Google Maps geocoder url to fetch information about @p address.
151 // Returns the built url.
152 private function getGeocodingUrl($address) {
156 'key' => $globals->geocoder
->gmaps_key
,
157 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
158 'hl' => 'fr', // Output langage.
159 'oe' => 'utf8', // Output encoding.
160 'output' => 'json', // Output format.
161 'gl' => 'fr', // Location preferences (addresses are in France by default).
162 'q' => $address, // The queries address.
165 return $globals->geocoder
->gmaps_url
. '?' . http_build_query($parameters);
168 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
169 // Returns the json array on success, and null otherwise.
170 private function getGeoJsonFromUrl($url) {
173 // Prepare a backtrace object to log errors.
175 if ($globals->debug
& DEBUG_BT
) {
176 if (!isset(PlBacktrace
::$bt['Geoloc'])) {
177 new PlBacktrace('Geoloc');
179 $bt = &PlBacktrace
::$bt['Geoloc'];
183 // Fetch the geocoding data.
184 $rawData = file_get_contents($url);
187 $bt->stop(0, "Could not retrieve geocoded address from GoogleMaps.");
192 // Decode the JSON-encoded data, and check for their validity.
193 $data = json_decode($rawData, true
);
195 $bt->stop(count($data), null
, $data);
201 // Extracts the most appropriate placemark from the JSON data fetched from
202 // Google Maps. Returns a Placemark array on success, and null otherwise. See
203 // http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured
204 // for details on the Placemark structure.
205 private function getPlacemarkFromJson(array $data) {
206 // Check for geocoding failures.
207 if (!isset($data['Status']['code']) ||
$data['Status']['code'] != 200) {
208 // TODO: handle non-200 codes in a better way, since the code might
209 // indicate a temporary error on Google's side.
213 // Check that at least one placemark was found.
214 if (count($data['Placemark']) == 0) {
218 // Extract the placemark with the best accuracy. This is not always the
219 // best result (since the same address may yield two different placemarks).
220 $result = $data['Placemark'][0];
221 foreach ($data['Placemark'] as $place) {
222 if ($place['AddressDetails']['Accuracy'] > $result['AddressDetails']['Accuracy']) {
230 // Fills the address with the geocoded data
231 private function fillAddressWithGeocoding(&$address, $geocodedData) {
232 // The geocoded address three is
233 // Country -> AdministrativeArea -> SubAdministrativeArea -> Locality -> Thoroughfare
234 // with all the possible shortcuts
235 // The address is formatted as xAL, or eXtensible Address Language, an international
236 // standard for address formatting.
237 // xAL documentation: http://www.oasis-open.org/committees/ciq/ciq.html#6
238 $address['geoloc'] = str_replace(", ", "\n", $geocodedData['address']);
239 if (isset($geocodedData['AddressDetails']['Accuracy'])) {
240 $address['accuracy'] = $geocodedData['AddressDetails']['Accuracy'];
243 $currentPosition = $geocodedData['AddressDetails'];
244 if (isset($currentPosition['Country'])) {
245 $currentPosition = $currentPosition['Country'];
246 $address['countryId'] = $currentPosition['CountryNameCode'];
247 $address['country'] = $currentPosition['CountryName'];
249 if (isset($currentPosition['AdministrativeArea'])) {
250 $currentPosition = $currentPosition['AdministrativeArea'];
251 $address['administrativeAreaName'] = $currentPosition['AdministrativeAreaName'];
253 if (isset($currentPosition['SubAdministrativeArea'])) {
254 $currentPosition = $currentPosition['SubAdministrativeArea'];
255 $address['subAdministrativeAreaName'] = $currentPosition['SubAdministrativeAreaName'];
257 if (isset($currentPosition['Locality'])) {
258 $currentPosition = $currentPosition['Locality'];
259 $address['localityName'] = $currentPosition['LocalityName'];
261 if (isset($currentPosition['Thoroughfare'])) {
262 $address['thoroughfareName'] = $currentPosition['Thoroughfare']['ThoroughfareName'];
264 if (isset($currentPosition['PostalCode'])) {
265 $address['postalCode'] = $currentPosition['PostalCode']['PostalCodeNumber'];
269 if (isset($geocodedData['Point']['coordinates'][0])) {
270 $address['latitude'] = $geocodedData['Point']['coordinates'][0];
272 if (isset($geocodedData['Point']['coordinates'][1])) {
273 $address['longitude'] = $geocodedData['Point']['coordinates'][1];
275 if (isset($geocodedData['ExtendedData']['LatLonBox']['north'])) {
276 $address['north'] = $geocodedData['ExtendedData']['LatLonBox']['north'];
278 if (isset($geocodedData['ExtendedData']['LatLonBox']['south'])) {
279 $address['south'] = $geocodedData['ExtendedData']['LatLonBox']['south'];
281 if (isset($geocodedData['ExtendedData']['LatLonBox']['east'])) {
282 $address['east'] = $geocodedData['ExtendedData']['LatLonBox']['east'];
284 if (isset($geocodedData['ExtendedData']['LatLonBox']['west'])) {
285 $address['west'] = $geocodedData['ExtendedData']['LatLonBox']['west'];
289 // Formats the text of the geocoded address using the unused data and
290 // compares it to the given address. If they are too different, the user
291 // will be asked to choose between them.
292 private function formatAddress(&$address, $extraLines) {
295 $address['geoloc'] = $extraLines . "\n" . $address['geoloc'];
297 $geoloc = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
298 array("", "\n"), $address['geoloc']));
299 $text = strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
300 array("", "\n"), $address['text']));
301 $arrayGeoloc = explode("\n", $geoloc);
302 $arrayText = explode("\n", $text);
303 $countGeoloc = count($arrayGeoloc);
304 $countText = count($arrayText);
306 if (($countText > $countGeoloc) ||
($countText < $countGeoloc - 1)
307 ||
(($countText == $countGeoloc - 1)
308 && ($arrayText[$countText - 1] == strtoupper($address['country'])))) {
311 for ($i = 0; $i < $countGeoloc && $i < $countText; ++
$i) {
312 if (levenshtein($arrayText[$i], trim($arrayGeoloc[$i])) > 3) {
318 $address['text'] = $address['geoloc'];
319 unset($address['geoloc']);
323 // Search for the lign from the given address that is the closest to the geocoded thoroughfareName
324 // and replaces the corresponding lign in the geocoded text by it.
325 static protected function fixStreetNumber(&$address)
327 if (isset($address['thoroughfareName'])) {
328 $thoroughfareName = $address['thoroughfareName'];
329 $thoroughfareToken = strtoupper(trim(preg_replace(array("/[,\"'#~:;_\-]/", "/\r\n/"),
330 array("", "\n"), $thoroughfareName)));
331 $geolocLines = explode("\n", $address['geoloc']);
332 $textLines = explode("\n", $address['text']);
333 $mindist = strlen($thoroughfareToken);
336 foreach ($textLines as $i => $token) {
337 if (($l = levenshtein(strtoupper(trim(preg_replace(array("/[,\"'#~:;_\-]/", "/\r\n/"),
338 array("", "\n"), $token))),
339 $thoroughfareToken)) < $mindist) {
344 foreach ($geolocLines as $i => $line) {
345 if (strtoupper(trim($thoroughfareName)) == strtoupper(trim($line))) {
350 $geolocLines[$pos] = $textLines[$minpos];
351 $address['geoloc'] = implode("\n", $geolocLines);
356 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: