Updates map on address edition.
[platal.git] / classes / gmapsgeocoder.php
CommitLineData
4c906759
SJ
1<?php
2/***************************************************************************
12262f13 3 * Copyright (C) 2003-2011 Polytechnique.org *
4c906759
SJ
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
0f5f1b70
SJ
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/
4c906759 25//
0f5f1b70
SJ
26// It requires the properties gmaps_url to be defined in section Geocoder
27// in plat/al's configuration (platal.ini & platal.conf).
4c906759
SJ
28class GMapsGeocoder extends Geocoder {
29
30 // Maximum number of Geocoding calls to the Google Maps API.
31 const MAX_GMAPS_RPC_CALLS = 5;
32
b1f39e8b
SJ
33 static public function buildStaticMapURL($latitude, $longitude, $color, $separator = '&')
34 {
35 $parameters = array(
36 'size' => '300x100',
37 'markers' => 'color:' . $color . '|' . $latitude . ',' . $longitude,
38 'zoom' => '12',
39 'sensor' => 'false'
40 );
41 global $globals;
42
43 return Platal::globals()->maps->static_map . '?' . http_build_query($parameters, '', $separator);
44 }
45
26ba053e 46 public function getGeocodedAddress(Address $address, $defaultLanguage = null, $forceLanguage = false) {
4e7a3faa
SJ
47 $this->prepareAddress($address);
48 $textAddress = $this->getTextToGeocode($address->text);
2ffc0393 49 if (is_null($defaultLanguage)) {
0f5f1b70 50 $defaultLanguage = Platal::globals()->geocoder->gmaps_language;
2ffc0393 51 }
4c906759
SJ
52
53 // Try to geocode the full address.
72a4c6a8 54 $address->geocoding_calls = 1;
2ffc0393
SJ
55 if (($geocodedData = $this->getPlacemarkForAddress($textAddress, $defaultLanguage))) {
56 $this->getUpdatedAddress($address, $geocodedData, null, $forceLanguage);
4e7a3faa 57 return;
4c906759
SJ
58 }
59
60 // If the full geocoding failed, try to geocode only the final part of the address.
61 // We start by geocoding everything but the first line, and continue until we get
62 // a result. To respect the limit of GMaps calls, we ignore the first few lines
63 // if there are too many address lines.
64 $addressLines = explode("\n", $textAddress);
65 $linesCount = count($addressLines);
66 for ($i = max(1, $linesCount - self::MAX_GMAPS_RPC_CALLS + 1); $i < $linesCount; ++$i) {
67 $extraLines = implode("\n", array_slice($addressLines, 0, $i));
68 $toGeocode = implode("\n", array_slice($addressLines, $i));
72a4c6a8 69 ++$address->geocoding_calls;
2ffc0393
SJ
70 if (($geocodedData = $this->getPlacemarkForAddress($toGeocode, $defaultLanguage))) {
71 $this->getUpdatedAddress($address, $geocodedData, $extraLines, $forceLanguage);
4e7a3faa 72 return;
4c906759
SJ
73 }
74 }
4c906759
SJ
75 }
76
26ba053e 77 public function stripGeocodingFromAddress(Address $address) {
0f5f1b70
SJ
78 $address->formatted_address = '';
79 $address->types = '';
80 $address->latitude = null;
81 $address->longitude = null;
82 $address->southwest_latitude = null;
83 $address->southwest_longitude = null;
84 $address->northeast_latitude = null;
85 $address->northeast_longitude = null;
86 $address->location_type = null;
87 $address->partial_match = false;
73f6c165 88 }
00e5200b 89
4c906759
SJ
90 // Updates the address with the geocoded information from Google Maps. Also
91 // cleans up the final informations.
26ba053e 92 private function getUpdatedAddress(Address $address, array $geocodedData, $extraLines, $forceLanguage) {
803612ae 93 $this->fillAddressWithGeocoding($address, $geocodedData, false);
2ffc0393 94 $this->formatAddress($address, $extraLines, $forceLanguage);
4c906759
SJ
95 }
96
97 // Retrieves the Placemark object (see #getPlacemarkFromJson()) for the @p
98 // address, by querying the Google Maps API. Returns the array on success,
99 // and null otherwise.
2ffc0393 100 private function getPlacemarkForAddress($address, $defaultLanguage) {
803612ae 101 $url = $this->getGeocodingUrl($address, $defaultLanguage);
4c906759
SJ
102 $geoData = $this->getGeoJsonFromUrl($url);
103
0f5f1b70 104 return ($geoData ? $this->getPlacemarkFromJson($geoData, $url) : null);
4c906759
SJ
105 }
106
107 // Prepares address to be geocoded
26ba053e 108 private function prepareAddress(Address $address) {
4e7a3faa 109 $address->text = preg_replace('/\s*\n\s*/m', "\n", trim($address->text));
4c906759
SJ
110 }
111
112 // Builds the Google Maps geocoder url to fetch information about @p address.
113 // Returns the built url.
803612ae 114 private function getGeocodingUrl($address, $defaultLanguage) {
4c906759
SJ
115 global $globals;
116
117 $parameters = array(
0f5f1b70
SJ
118 'language' => $defaultLanguage,
119 'region' => $globals->geocoder->gmaps_region,
120 'sensor' => 'false', // The queried address wasn't obtained from a GPS sensor.
121 'address' => $address, // The queries address.
4c906759
SJ
122 );
123
0f5f1b70 124 return $globals->geocoder->gmaps_url . 'json?' . http_build_query($parameters);
4c906759
SJ
125 }
126
127 // Fetches JSON-encoded data from a Google Maps API url, and decode them.
128 // Returns the json array on success, and null otherwise.
129 private function getGeoJsonFromUrl($url) {
130 global $globals;
131
132 // Prepare a backtrace object to log errors.
133 $bt = null;
134 if ($globals->debug & DEBUG_BT) {
135 if (!isset(PlBacktrace::$bt['Geoloc'])) {
136 new PlBacktrace('Geoloc');
137 }
138 $bt = &PlBacktrace::$bt['Geoloc'];
139 $bt->start($url);
140 }
141
142 // Fetch the geocoding data.
143 $rawData = file_get_contents($url);
144 if (!$rawData) {
145 if ($bt) {
4e7a3faa 146 $bt->stop(0, 'Could not retrieve geocoded address from GoogleMaps.');
4c906759
SJ
147 }
148 return null;
149 }
150
151 // Decode the JSON-encoded data, and check for their validity.
152 $data = json_decode($rawData, true);
153 if ($bt) {
154 $bt->stop(count($data), null, $data);
155 }
156
157 return $data;
158 }
159
160 // Extracts the most appropriate placemark from the JSON data fetched from
0f5f1b70
SJ
161 // Google Maps. Returns a Placemark array on success, and null otherwise.
162 // http://code.google.com/apis/maps/documentation/geocoding/#StatusCodes
163 private function getPlacemarkFromJson(array $data, $url) {
164 // Check for geocoding status.
165 $status = $data['status'];
166
167 // If no result, return null.
168 if ($status == 'ZERO_RESULTS') {
4c906759
SJ
169 return null;
170 }
171
0f5f1b70
SJ
172 // If there are results return the first one.
173 if ($status == 'OK') {
174 return $data['results'][0];
4c906759
SJ
175 }
176
0f5f1b70
SJ
177 // Report the error.
178 $mailer = new PlMailer('profile/geocoding.mail.tpl');
179 $mailer->assign('status', $status);
180 $mailer->assign('url', $url);
181 $mailer->send();
182 return null;
4c906759
SJ
183 }
184
185 // Fills the address with the geocoded data
26ba053e 186 private function fillAddressWithGeocoding(Address $address, $geocodedData, $isLocal) {
0f5f1b70
SJ
187 $address->types = implode(',', $geocodedData['types']);
188 $address->formatted_address = $geocodedData['formatted_address'];
189 $address->components = $geocodedData['address_components'];
190 $address->latitude = $geocodedData['geometry']['location']['lat'];
191 $address->longitude = $geocodedData['geometry']['location']['lng'];
192 $address->southwest_latitude = $geocodedData['geometry']['viewport']['southwest']['lat'];
193 $address->southwest_longitude = $geocodedData['geometry']['viewport']['southwest']['lng'];
194 $address->northeast_latitude = $geocodedData['geometry']['viewport']['northeast']['lat'];
195 $address->northeast_longitude = $geocodedData['geometry']['viewport']['northeast']['lng'];
196 $address->location_type = $geocodedData['geometry']['location_type'];
197 $address->partial_match = isset($geocodedData['partial_match']) ? true : false;
803612ae
SJ
198 }
199
200 // Formats the text of the geocoded address using the unused data and
201 // compares it to the given address. If they are too different, the user
202 // will be asked to choose between them.
26ba053e 203 private function formatAddress(Address $address, $extraLines, $forceLanguage)
803612ae 204 {
0f5f1b70
SJ
205 /* XXX: Check how to integrate this in the new geocoding system.
206 if (!$forceLanguage) {
2ffc0393 207 $languages = XDB::fetchOneCell('SELECT IF(ISNULL(gc1.belongsTo), gl1.language, gl2.language)
803612ae 208 FROM geoloc_countries AS gc1
2ffc0393 209 INNER JOIN geoloc_languages AS gl1 ON (gc1.iso_3166_1_a2 = gl1.iso_3166_1_a2)
803612ae 210 LEFT JOIN geoloc_countries AS gc2 ON (gc1.belongsTo = gc2.iso_3166_1_a2)
2ffc0393 211 LEFT JOIN geoloc_languages AS gl2 ON (gc2.iso_3166_1_a2 = gl2.iso_3166_1_a2)
803612ae
SJ
212 WHERE gc1.iso_3166_1_a2 = {?}',
213 $address->countryId);
214 $toGeocode = substr($address->text, strlen($extraLines));
215 foreach (explode(',', $languages) as $language) {
0f5f1b70 216 if ($language != Platal::globals()->geocoder->gmaps_language) {
803612ae 217 $geocodedData = $this->getPlacemarkForAddress($toGeocode, $language);
0f5f1b70
SJ
218 $this->fillAddressWithGeocoding($address, $geocodedData, true);
219 break;
803612ae
SJ
220 }
221 }
0f5f1b70 222 }*/
4e7a3faa 223 $address->text = str_replace("\n", "\r\n", $address->text);
5a10ab14
SJ
224 }
225
00e5200b
SJ
226 // Trims the name of the real country if it contains an ISO 3166-1 non-country
227 // item. For that purpose, we compare the last but one line of the address with
228 // all non-country items of ISO 3166-1.
4e7a3faa 229 private function getTextToGeocode($text)
00e5200b 230 {
1c305d4c 231 $res = XDB::iterator('SELECT countryEn, country
00e5200b
SJ
232 FROM geoloc_countries
233 WHERE belongsTo IS NOT NULL');
234 $countries = array();
235 foreach ($res as $item) {
236 $countries[] = $item[0];
237 $countries[] = $item[1];
238 }
4e7a3faa 239 $textLines = explode("\n", $text);
00e5200b
SJ
240 $countLines = count($textLines);
241 $needle = strtoupper(trim($textLines[$countLines - 2]));
242 $isPseudoCountry = false;
96c7ea54
SJ
243 if ($needle) {
244 foreach ($countries as $country) {
245 if (strtoupper($country) === $needle) {
246 $isPseudoCountry = true;
247 break;
248 }
00e5200b
SJ
249 }
250 }
251
252 if ($isPseudoCountry) {
02c4b93a 253 return implode("\n", array_slice($textLines, 0, -1));
00e5200b 254 }
4e7a3faa 255 return $text;
00e5200b 256 }
4c906759
SJ
257}
258
259// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
260?>