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 v3. Please refer
23 // to the following link for details:
24 // http://code.google.com/apis/maps/documentation/geocoding/
26 // It requires the properties gmaps_url to be defined in section Geocoder
27 // in plat/al's configuration (platal.ini & platal.conf).
28 class GMapsGeocoder
extends Geocoder
{
30 // Maximum number of Geocoding calls to the Google Maps API.
31 const MAX_GMAPS_RPC_CALLS
= 5;
33 public function getGeocodedAddress(Address
$address, $defaultLanguage = null
, $forceLanguage = false
) {
34 $this->prepareAddress($address);
35 $textAddress = $this->getTextToGeocode($address->text
);
36 if (is_null($defaultLanguage)) {
37 $defaultLanguage = Platal
::globals()->geocoder
->gmaps_language
;
40 // Try to geocode the full address.
41 if (($geocodedData = $this->getPlacemarkForAddress($textAddress, $defaultLanguage))) {
42 $this->getUpdatedAddress($address, $geocodedData, null
, $forceLanguage);
46 // If the full geocoding failed, try to geocode only the final part of the address.
47 // We start by geocoding everything but the first line, and continue until we get
48 // a result. To respect the limit of GMaps calls, we ignore the first few lines
49 // if there are too many address lines.
50 $addressLines = explode("\n", $textAddress);
51 $linesCount = count($addressLines);
52 for ($i = max(1, $linesCount - self
::MAX_GMAPS_RPC_CALLS +
1); $i < $linesCount; ++
$i) {
53 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
54 $toGeocode = implode("\n", array_slice($addressLines, $i));
55 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode, $defaultLanguage))) {
56 $this->getUpdatedAddress($address, $geocodedData, $extraLines, $forceLanguage);
62 public function stripGeocodingFromAddress(Address
$address) {
63 $address->formatted_address
= '';
65 $address->latitude
= null
;
66 $address->longitude
= null
;
67 $address->southwest_latitude
= null
;
68 $address->southwest_longitude
= null
;
69 $address->northeast_latitude
= null
;
70 $address->northeast_longitude
= null
;
71 $address->location_type
= null
;
72 $address->partial_match
= false
;
75 // Updates the address with the geocoded information from Google Maps. Also
76 // cleans up the final informations.
77 private function getUpdatedAddress(Address
$address, array $geocodedData, $extraLines, $forceLanguage) {
78 $this->fillAddressWithGeocoding($address, $geocodedData, false
);
79 $this->formatAddress($address, $extraLines, $forceLanguage);
82 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
83 // address, by querying the Google Maps API. Returns the array on success,
84 // and null otherwise.
85 private function getPlacemarkForAddress($address, $defaultLanguage) {
86 $url = $this->getGeocodingUrl($address, $defaultLanguage);
87 $geoData = $this->getGeoJsonFromUrl($url);
89 return ($geoData ?
$this->getPlacemarkFromJson($geoData, $url) : null
);
92 // Prepares address to be geocoded
93 private function prepareAddress(Address
$address) {
94 $address->text
= preg_replace('/\s*\n\s*/m', "\n", trim($address->text
));
97 // Builds the Google Maps geocoder url to fetch information about @p address.
98 // Returns the built url.
99 private function getGeocodingUrl($address, $defaultLanguage) {
103 'language' => $defaultLanguage,
104 'region' => $globals->geocoder
->gmaps_region
,
105 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
106 'address' => $address, // The queries address.
109 return $globals->geocoder
->gmaps_url
. 'json?' . http_build_query($parameters);
112 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
113 // Returns the json array on success, and null otherwise.
114 private function getGeoJsonFromUrl($url) {
117 // Prepare a backtrace object to log errors.
119 if ($globals->debug
& DEBUG_BT
) {
120 if (!isset(PlBacktrace
::$bt['Geoloc'])) {
121 new PlBacktrace('Geoloc');
123 $bt = &PlBacktrace
::$bt['Geoloc'];
127 // Fetch the geocoding data.
128 $rawData = file_get_contents($url);
131 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
136 // Decode the JSON-encoded data, and check for their validity.
137 $data = json_decode($rawData, true
);
139 $bt->stop(count($data), null
, $data);
145 // Extracts the most appropriate placemark from the JSON data fetched from
146 // Google Maps. Returns a Placemark array on success, and null otherwise.
147 // http://code.google.com/apis/maps/documentation/geocoding/#StatusCodes
148 private function getPlacemarkFromJson(array $data, $url) {
149 // Check for geocoding status.
150 $status = $data['status'];
152 // If no result, return null.
153 if ($status == 'ZERO_RESULTS') {
157 // If there are results return the first one.
158 if ($status == 'OK') {
159 return $data['results'][0];
163 $mailer = new PlMailer('profile/geocoding.mail.tpl');
164 $mailer->assign('status', $status);
165 $mailer->assign('url', $url);
170 // Fills the address with the geocoded data
171 private function fillAddressWithGeocoding(Address
$address, $geocodedData, $isLocal) {
172 $address->types
= implode(',', $geocodedData['types']);
173 $address->formatted_address
= $geocodedData['formatted_address'];
174 $address->components
= $geocodedData['address_components'];
175 $address->latitude
= $geocodedData['geometry']['location']['lat'];
176 $address->longitude
= $geocodedData['geometry']['location']['lng'];
177 $address->southwest_latitude
= $geocodedData['geometry']['viewport']['southwest']['lat'];
178 $address->southwest_longitude
= $geocodedData['geometry']['viewport']['southwest']['lng'];
179 $address->northeast_latitude
= $geocodedData['geometry']['viewport']['northeast']['lat'];
180 $address->northeast_longitude
= $geocodedData['geometry']['viewport']['northeast']['lng'];
181 $address->location_type
= $geocodedData['geometry']['location_type'];
182 $address->partial_match
= isset($geocodedData['partial_match']) ? true
: false
;
185 // Formats the text of the geocoded address using the unused data and
186 // compares it to the given address. If they are too different, the user
187 // will be asked to choose between them.
188 private function formatAddress(Address
$address, $extraLines, $forceLanguage)
190 /* XXX: Check how to integrate this in the new geocoding system.
191 if (!$forceLanguage) {
192 $languages = XDB::fetchOneCell('SELECT IF(ISNULL(gc1.belongsTo), gl1.language, gl2.language)
193 FROM geoloc_countries AS gc1
194 INNER JOIN geoloc_languages AS gl1 ON (gc1.iso_3166_1_a2 = gl1.iso_3166_1_a2)
195 LEFT JOIN geoloc_countries AS gc2 ON (gc1.belongsTo = gc2.iso_3166_1_a2)
196 LEFT JOIN geoloc_languages AS gl2 ON (gc2.iso_3166_1_a2 = gl2.iso_3166_1_a2)
197 WHERE gc1.iso_3166_1_a2 = {?}',
198 $address->countryId);
199 $toGeocode = substr($address->text, strlen($extraLines));
200 foreach (explode(',', $languages) as $language) {
201 if ($language != Platal::globals()->geocoder->gmaps_language) {
202 $geocodedData = $this->getPlacemarkForAddress($toGeocode, $language);
203 $this->fillAddressWithGeocoding($address, $geocodedData, true);
208 $address->text
= str_replace("\n", "\r\n", $address->text
);
211 // Trims the name of the real country if it contains an ISO 3166-1 non-country
212 // item. For that purpose, we compare the last but one line of the address with
213 // all non-country items of ISO 3166-1.
214 private function getTextToGeocode($text)
216 $res = XDB
::iterator('SELECT countryEn, country
217 FROM geoloc_countries
218 WHERE belongsTo IS NOT NULL');
219 $countries = array();
220 foreach ($res as $item) {
221 $countries[] = $item[0];
222 $countries[] = $item[1];
224 $textLines = explode("\n", $text);
225 $countLines = count($textLines);
226 $needle = strtoupper(trim($textLines[$countLines - 2]));
227 $isPseudoCountry = false
;
229 foreach ($countries as $country) {
230 if (strtoupper($country) === $needle) {
231 $isPseudoCountry = true
;
237 if ($isPseudoCountry) {
238 return implode("\n", array_slice($textLines, 0, -1));
244 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: