5 require_once(CONST_LibDir.'/AddressDetails.php');
6 require_once(CONST_LibDir.'/Result.php');
12 protected $aLangPrefOrderSql = "''";
14 protected $bAddressDetails = false;
15 protected $bExtraTags = false;
16 protected $bNameDetails = false;
18 protected $bIncludePolygonAsText = false;
19 protected $bIncludePolygonAsGeoJSON = false;
20 protected $bIncludePolygonAsKML = false;
21 protected $bIncludePolygonAsSVG = false;
22 protected $fPolygonSimplificationThreshold = 0.0;
24 protected $sAnchorSql = null;
25 protected $sAddressRankListSql = null;
26 protected $sAllowedTypesSQLList = null;
27 protected $bDeDupe = true;
30 public function __construct(&$oDB)
35 public function doDeDupe()
37 return $this->bDeDupe;
40 public function setIncludeAddressDetails($b)
42 $this->bAddressDetails = $b;
45 public function loadParamArray($oParams, $sGeomType = null)
47 $aLangs = $oParams->getPreferredLanguages();
48 $this->aLangPrefOrderSql =
49 'ARRAY['.join(',', $this->oDB->getDBQuotedList($aLangs)).']';
51 $this->bExtraTags = $oParams->getBool('extratags', false);
52 $this->bNameDetails = $oParams->getBool('namedetails', false);
54 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
56 if ($sGeomType === null || $sGeomType == 'geojson') {
57 $this->bIncludePolygonAsGeoJSON = $oParams->getBool('polygon_geojson');
60 if ($oParams->getString('format', '') !== 'geojson') {
61 if ($sGeomType === null || $sGeomType == 'text') {
62 $this->bIncludePolygonAsText = $oParams->getBool('polygon_text');
64 if ($sGeomType === null || $sGeomType == 'kml') {
65 $this->bIncludePolygonAsKML = $oParams->getBool('polygon_kml');
67 if ($sGeomType === null || $sGeomType == 'svg') {
68 $this->bIncludePolygonAsSVG = $oParams->getBool('polygon_svg');
71 $this->fPolygonSimplificationThreshold
72 = $oParams->getFloat('polygon_threshold', 0.0);
75 ($this->bIncludePolygonAsText ? 1 : 0) +
76 ($this->bIncludePolygonAsGeoJSON ? 1 : 0) +
77 ($this->bIncludePolygonAsKML ? 1 : 0) +
78 ($this->bIncludePolygonAsSVG ? 1 : 0);
79 if ($iWantedTypes > CONST_PolygonOutput_MaximumTypes) {
80 if (CONST_PolygonOutput_MaximumTypes) {
81 userError('Select only '.CONST_PolygonOutput_MaximumTypes.' polgyon output option');
83 userError('Polygon output is disabled');
88 public function getMoreUrlParams()
92 if ($this->bAddressDetails) $aParams['addressdetails'] = '1';
93 if ($this->bExtraTags) $aParams['extratags'] = '1';
94 if ($this->bNameDetails) $aParams['namedetails'] = '1';
96 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
97 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
98 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
99 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
101 if ($this->fPolygonSimplificationThreshold > 0.0) {
102 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
105 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
110 public function setAnchorSql($sPoint)
112 $this->sAnchorSql = $sPoint;
115 public function setAddressRankList($aList)
117 $this->sAddressRankListSql = '('.join(',', $aList).')';
120 public function setAllowedTypesSQLList($sSql)
122 $this->sAllowedTypesSQLList = $sSql;
125 public function setLanguagePreference($aLangPrefOrder)
127 $this->aLangPrefOrderSql = $this->oDB->getArraySQL(
128 $this->oDB->getDBQuotedList($aLangPrefOrder)
132 private function addressImportanceSql($sGeometry, $sPlaceId)
134 if ($this->sAnchorSql) {
135 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
137 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
138 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
139 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
140 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
141 $sSQL .= ' AND ai_s.isaddress ';
142 $sSQL .= ' AND ai_p.importance is not null)';
145 return $sSQL.' AS addressimportance,';
148 private function langAddressSql($sHousenumber)
150 if ($this->bAddressDetails)
151 return ''; // langaddress will be computed from address details
153 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
156 public function lookupOSMID($sType, $iID)
158 $sSQL = 'select place_id from placex where osm_type = :type and osm_id = :id';
159 $iPlaceID = $this->oDB->getOne($sSQL, array(':type' => $sType, ':id' => $iID));
165 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
167 return empty($aResults) ? null : reset($aResults);
170 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
172 Debug::newFunction('Place lookup');
174 if (empty($aResults)) {
177 $aSubSelects = array();
179 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
181 Debug::printVar('Ids from placex', $sPlaceIDs);
183 $sSQL .= ' osm_type,';
187 $sSQL .= ' admin_level,';
188 $sSQL .= ' rank_search,';
189 $sSQL .= ' rank_address,';
190 $sSQL .= ' min(place_id) AS place_id,';
191 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
192 $sSQL .= ' -1 as housenumber,';
193 $sSQL .= ' country_code,';
194 $sSQL .= $this->langAddressSql('-1');
195 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
196 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
197 if ($this->bExtraTags) {
198 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
200 if ($this->bNameDetails) {
201 $sSQL .= 'hstore_to_json(name)::text AS names,';
203 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
204 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
205 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
206 $sSQL .= $this->addressImportanceSql(
207 'ST_Collect(centroid)',
208 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
210 $sSQL .= " COALESCE(extratags->'place', extratags->'linked_place') AS extra_place ";
211 $sSQL .= ' FROM placex';
212 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
214 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
215 if (14 >= $iMinRank && 14 <= $iMaxRank) {
216 $sSQL .= " OR (extratags->'place') = 'city'";
218 if ($this->sAddressRankListSql) {
219 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
222 if ($this->sAllowedTypesSQLList) {
223 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
225 $sSQL .= ' AND linked_place_id is null ';
226 $sSQL .= ' GROUP BY ';
227 $sSQL .= ' osm_type, ';
228 $sSQL .= ' osm_id, ';
231 $sSQL .= ' admin_level, ';
232 $sSQL .= ' rank_search, ';
233 $sSQL .= ' rank_address, ';
234 $sSQL .= ' housenumber,';
235 $sSQL .= ' country_code, ';
236 $sSQL .= ' importance, ';
237 if (!$this->bDeDupe) $sSQL .= 'place_id,';
238 if (!$this->bAddressDetails) $sSQL .= 'langaddress, ';
239 $sSQL .= ' placename, ';
241 if ($this->bExtraTags) $sSQL .= 'extratags, ';
242 if ($this->bNameDetails) $sSQL .= 'name, ';
243 $sSQL .= ' extra_place ';
245 $aSubSelects[] = $sSQL;
249 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
251 Debug::printVar('Ids from location_postcode', $sPlaceIDs);
253 $sSQL .= " 'P' as osm_type,";
254 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,';
255 $sSQL .= " 'place' as class, 'postcode' as type,";
256 $sSQL .= ' null::smallint as admin_level, rank_search, rank_address,';
257 $sSQL .= ' place_id, parent_place_id,';
258 $sSQL .= ' -1 as housenumber,';
259 $sSQL .= ' country_code,';
260 $sSQL .= $this->langAddressSql('-1');
261 $sSQL .= ' postcode as placename,';
262 $sSQL .= ' postcode as ref,';
263 if ($this->bExtraTags) $sSQL .= 'null::text AS extra,';
264 if ($this->bNameDetails) $sSQL .= 'null::text AS names,';
265 $sSQL .= ' ST_x(geometry) AS lon, ST_y(geometry) AS lat,';
266 $sSQL .= ' (0.75-(rank_search::float/40)) AS importance, ';
267 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
268 $sSQL .= ' null::text AS extra_place ';
269 $sSQL .= 'FROM location_postcode lp';
270 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
271 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
273 $aSubSelects[] = $sSQL;
276 // All other tables are rank 30 only.
277 if ($iMaxRank == 30) {
279 if (CONST_Use_US_Tiger_Data) {
280 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
282 Debug::printVar('Ids from Tiger table', $sPlaceIDs);
283 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
284 // Tiger search only if a housenumber was searched and if it was found
285 // (realized through a join)
287 $sSQL .= " 'T' AS osm_type, ";
288 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ';
289 $sSQL .= " 'place' AS class, ";
290 $sSQL .= " 'house' AS type, ";
291 $sSQL .= ' null::smallint AS admin_level, ';
292 $sSQL .= ' 30 AS rank_search, ';
293 $sSQL .= ' 30 AS rank_address, ';
294 $sSQL .= ' place_id, ';
295 $sSQL .= ' parent_place_id, ';
296 $sSQL .= ' housenumber_for_place as housenumber,';
297 $sSQL .= " 'us' AS country_code, ";
298 $sSQL .= $this->langAddressSql('housenumber_for_place');
299 $sSQL .= ' null::text AS placename, ';
300 $sSQL .= ' null::text AS ref, ';
301 if ($this->bExtraTags) $sSQL .= 'null::text AS extra,';
302 if ($this->bNameDetails) $sSQL .= 'null::text AS names,';
303 $sSQL .= ' st_x(centroid) AS lon, ';
304 $sSQL .= ' st_y(centroid) AS lat,';
305 $sSQL .= ' -1.15 AS importance, ';
306 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
307 $sSQL .= ' null::text AS extra_place ';
309 $sSQL .= ' SELECT place_id, '; // interpolate the Tiger housenumbers here
310 $sSQL .= ' ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ';
311 $sSQL .= ' parent_place_id, ';
312 $sSQL .= ' housenumber_for_place';
314 $sSQL .= ' location_property_tiger ';
315 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
317 $sSQL .= ' housenumber_for_place >= startnumber';
318 $sSQL .= ' AND housenumber_for_place <= endnumber';
319 $sSQL .= ' ) AS blub'; //postgres wants an alias here
321 $aSubSelects[] = $sSQL;
325 // osmline - interpolated housenumbers
326 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
328 Debug::printVar('Ids from interpolation', $sPlaceIDs);
329 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
330 // interpolation line search only if a housenumber was searched
331 // (realized through a join)
333 $sSQL .= " 'W' AS osm_type, ";
334 $sSQL .= ' osm_id, ';
335 $sSQL .= " 'place' AS class, ";
336 $sSQL .= " 'house' AS type, ";
337 $sSQL .= ' null::smallint AS admin_level, ';
338 $sSQL .= ' 30 AS rank_search, ';
339 $sSQL .= ' 30 AS rank_address, ';
340 $sSQL .= ' place_id, ';
341 $sSQL .= ' parent_place_id, ';
342 $sSQL .= ' housenumber_for_place as housenumber,';
343 $sSQL .= ' country_code, ';
344 $sSQL .= $this->langAddressSql('housenumber_for_place');
345 $sSQL .= ' null::text AS placename, ';
346 $sSQL .= ' null::text AS ref, ';
347 if ($this->bExtraTags) $sSQL .= 'null::text AS extra, ';
348 if ($this->bNameDetails) $sSQL .= 'null::text AS names, ';
349 $sSQL .= ' st_x(centroid) AS lon, ';
350 $sSQL .= ' st_y(centroid) AS lat, ';
351 // slightly smaller than the importance for normal houses
352 $sSQL .= ' -0.1 AS importance, ';
353 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
354 $sSQL .= ' null::text AS extra_place ';
357 $sSQL .= ' osm_id, ';
358 $sSQL .= ' place_id, ';
359 $sSQL .= ' country_code, ';
360 $sSQL .= ' CASE '; // interpolate the housenumbers here
361 $sSQL .= ' WHEN startnumber != endnumber ';
362 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ';
363 $sSQL .= ' ELSE ST_LineInterpolatePoint(linegeo, 0.5) ';
364 $sSQL .= ' END as centroid, ';
365 $sSQL .= ' parent_place_id, ';
366 $sSQL .= ' housenumber_for_place ';
368 $sSQL .= ' location_property_osmline ';
369 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
371 $sSQL .= ' WHERE housenumber_for_place >= 0 ';
372 $sSQL .= ' ) as blub'; //postgres wants an alias here
374 $aSubSelects[] = $sSQL;
378 if (empty($aSubSelects)) {
382 $sSQL = join(' UNION ', $aSubSelects);
383 Debug::printSQL($sSQL);
384 $aPlaces = $this->oDB->getAll($sSQL, null, 'Could not lookup place');
386 foreach ($aPlaces as &$aPlace) {
387 $aPlace['importance'] = (float) $aPlace['importance'];
388 if ($this->bAddressDetails) {
389 // to get addressdetails for tiger data, the housenumber is needed
390 $aPlace['address'] = new AddressDetails(
393 $aPlace['housenumber'],
394 $this->aLangPrefOrderSql
396 $aPlace['langaddress'] = $aPlace['address']->getLocaleAddress();
399 if ($this->bExtraTags) {
400 if ($aPlace['extra']) {
401 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
403 $aPlace['sExtraTags'] = (object) array();
407 if ($this->bNameDetails) {
408 if ($aPlace['names']) {
409 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
411 $aPlace['sNameDetails'] = (object) array();
415 $aPlace['addresstype'] = ClassTypes\getLabelTag(
417 $aPlace['country_code']
420 $aResults[$aPlace['place_id']] = $aPlace;
423 $aResults = array_filter(
426 return !($v instanceof Result);
430 Debug::printVar('Places', $aResults);
435 /* returns an array which will contain the keys
437 * and may also contain one or more of the keys
447 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
450 $aOutlineResult = array();
451 if (!$iPlaceID) return $aOutlineResult;
453 // Get the bounding box and outline polygon
454 $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
455 if ($fLonReverse != null && $fLatReverse != null) {
456 $sSQL .= ' ST_Y(closest_point) as centrelat,';
457 $sSQL .= ' ST_X(closest_point) as centrelon,';
459 $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
461 $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
462 $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
463 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
464 if ($this->bIncludePolygonAsKML) $sSQL .= ',ST_AsKML(geometry) as askml';
465 if ($this->bIncludePolygonAsSVG) $sSQL .= ',ST_AsSVG(geometry) as assvg';
466 if ($this->bIncludePolygonAsText) $sSQL .= ',ST_AsText(geometry) as astext';
467 if ($fLonReverse != null && $fLatReverse != null) {
468 $sFrom = ' from (SELECT * , CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
469 $sFrom .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
470 $sFrom .=' ELSE centroid END AS closest_point';
471 $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
473 $sFrom = ' from placex where place_id = '.$iPlaceID;
475 if ($this->fPolygonSimplificationThreshold > 0) {
476 $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
481 $aPointPolygon = $this->oDB->getRow($sSQL, null, 'Could not get outline');
483 if ($aPointPolygon && $aPointPolygon['place_id']) {
484 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
485 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
486 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
489 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
490 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
491 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
492 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
494 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
495 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
496 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
499 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
500 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
501 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
504 $aOutlineResult['aBoundingBox'] = array(
505 (string)$aPointPolygon['minlat'],
506 (string)$aPointPolygon['maxlat'],
507 (string)$aPointPolygon['minlon'],
508 (string)$aPointPolygon['maxlon']
512 // as a fallback we generate a bounding box without knowing the size of the geometry
513 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
515 'minlat' => $fLat - $fRadius,
516 'maxlat' => $fLat + $fRadius,
517 'minlon' => $fLon - $fRadius,
518 'maxlon' => $fLon + $fRadius
521 $aOutlineResult['aBoundingBox'] = array(
522 (string)$aBounds['minlat'],
523 (string)$aBounds['maxlat'],
524 (string)$aBounds['minlon'],
525 (string)$aBounds['maxlon']
528 return $aOutlineResult;