3 * SPDX-License-Identifier: GPL-2.0-only
5 * This file is part of Nominatim. (https://nominatim.org)
7 * Copyright (C) 2022 by the Nominatim developer community.
8 * For a full list of authors see the git log.
13 require_once(CONST_LibDir.'/AddressDetails.php');
14 require_once(CONST_LibDir.'/Result.php');
20 protected $aLangPrefOrderSql = "''";
22 protected $bAddressDetails = false;
23 protected $bExtraTags = false;
24 protected $bNameDetails = false;
26 protected $bIncludePolygonAsText = false;
27 protected $bIncludePolygonAsGeoJSON = false;
28 protected $bIncludePolygonAsKML = false;
29 protected $bIncludePolygonAsSVG = false;
30 protected $fPolygonSimplificationThreshold = 0.0;
32 protected $sAnchorSql = null;
33 protected $sAddressRankListSql = null;
34 protected $sAllowedTypesSQLList = null;
35 protected $bDeDupe = true;
38 public function __construct(&$oDB)
43 public function doDeDupe()
45 return $this->bDeDupe;
48 public function setIncludeAddressDetails($b)
50 $this->bAddressDetails = $b;
53 public function loadParamArray($oParams, $sGeomType = null)
55 $aLangs = $oParams->getPreferredLanguages();
56 $this->aLangPrefOrderSql =
57 'ARRAY['.join(',', $this->oDB->getDBQuotedList($aLangs)).']';
59 $this->bExtraTags = $oParams->getBool('extratags', false);
60 $this->bNameDetails = $oParams->getBool('namedetails', false);
62 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
64 if ($sGeomType === null || $sGeomType == 'geojson') {
65 $this->bIncludePolygonAsGeoJSON = $oParams->getBool('polygon_geojson');
68 if ($oParams->getString('format', '') !== 'geojson') {
69 if ($sGeomType === null || $sGeomType == 'text') {
70 $this->bIncludePolygonAsText = $oParams->getBool('polygon_text');
72 if ($sGeomType === null || $sGeomType == 'kml') {
73 $this->bIncludePolygonAsKML = $oParams->getBool('polygon_kml');
75 if ($sGeomType === null || $sGeomType == 'svg') {
76 $this->bIncludePolygonAsSVG = $oParams->getBool('polygon_svg');
79 $this->fPolygonSimplificationThreshold
80 = $oParams->getFloat('polygon_threshold', 0.0);
83 ($this->bIncludePolygonAsText ? 1 : 0) +
84 ($this->bIncludePolygonAsGeoJSON ? 1 : 0) +
85 ($this->bIncludePolygonAsKML ? 1 : 0) +
86 ($this->bIncludePolygonAsSVG ? 1 : 0);
87 if ($iWantedTypes > CONST_PolygonOutput_MaximumTypes) {
88 if (CONST_PolygonOutput_MaximumTypes) {
89 userError('Select only '.CONST_PolygonOutput_MaximumTypes.' polgyon output option');
91 userError('Polygon output is disabled');
96 public function getMoreUrlParams()
100 if ($this->bAddressDetails) {
101 $aParams['addressdetails'] = '1';
103 if ($this->bExtraTags) {
104 $aParams['extratags'] = '1';
106 if ($this->bNameDetails) {
107 $aParams['namedetails'] = '1';
110 if ($this->bIncludePolygonAsText) {
111 $aParams['polygon_text'] = '1';
113 if ($this->bIncludePolygonAsGeoJSON) {
114 $aParams['polygon_geojson'] = '1';
116 if ($this->bIncludePolygonAsKML) {
117 $aParams['polygon_kml'] = '1';
119 if ($this->bIncludePolygonAsSVG) {
120 $aParams['polygon_svg'] = '1';
123 if ($this->fPolygonSimplificationThreshold > 0.0) {
124 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
127 if (!$this->bDeDupe) {
128 $aParams['dedupe'] = '0';
134 public function setAnchorSql($sPoint)
136 $this->sAnchorSql = $sPoint;
139 public function setAddressRankList($aList)
141 $this->sAddressRankListSql = '('.join(',', $aList).')';
144 public function setAllowedTypesSQLList($sSql)
146 $this->sAllowedTypesSQLList = $sSql;
149 public function setLanguagePreference($aLangPrefOrder)
151 $this->aLangPrefOrderSql = $this->oDB->getArraySQL(
152 $this->oDB->getDBQuotedList($aLangPrefOrder)
156 private function addressImportanceSql($sGeometry, $sPlaceId)
158 if ($this->sAnchorSql) {
159 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
161 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
162 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
163 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
164 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
165 $sSQL .= ' AND ai_s.isaddress ';
166 $sSQL .= ' AND ai_p.importance is not null)';
169 return $sSQL.' AS addressimportance,';
172 private function langAddressSql($sHousenumber)
174 if ($this->bAddressDetails) {
175 return ''; // langaddress will be computed from address details
178 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
181 public function lookupOSMID($sType, $iID)
183 $sSQL = 'select place_id from placex where osm_type = :type and osm_id = :id';
184 $iPlaceID = $this->oDB->getOne($sSQL, array(':type' => $sType, ':id' => $iID));
190 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)), 0, 30, true);
192 return empty($aResults) ? null : reset($aResults);
195 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30, $bAllowLinked = false)
197 Debug::newFunction('Place lookup');
199 if (empty($aResults)) {
202 $aSubSelects = array();
204 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
206 Debug::printVar('Ids from placex', $sPlaceIDs);
208 $sSQL .= ' osm_type,';
212 $sSQL .= ' admin_level,';
213 $sSQL .= ' rank_search,';
214 $sSQL .= ' rank_address,';
215 $sSQL .= ' min(place_id) AS place_id,';
216 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
217 $sSQL .= ' -1 as housenumber,';
218 $sSQL .= ' country_code,';
219 $sSQL .= $this->langAddressSql('-1');
220 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
221 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
222 if ($this->bExtraTags) {
223 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
225 if ($this->bNameDetails) {
226 $sSQL .= 'hstore_to_json(name)::text AS names,';
228 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
229 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
230 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
231 $sSQL .= $this->addressImportanceSql(
232 'ST_Collect(centroid)',
233 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
235 $sSQL .= " COALESCE(extratags->'place', extratags->'linked_place') AS extra_place ";
236 $sSQL .= ' FROM placex';
237 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
239 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
240 if (14 >= $iMinRank && 14 <= $iMaxRank) {
241 $sSQL .= " OR (extratags->'place') = 'city'";
243 if ($this->sAddressRankListSql) {
244 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
247 if ($this->sAllowedTypesSQLList) {
248 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
250 if (!$bAllowLinked) {
251 $sSQL .= ' AND linked_place_id is null ';
253 $sSQL .= ' GROUP BY ';
254 $sSQL .= ' osm_type, ';
255 $sSQL .= ' osm_id, ';
258 $sSQL .= ' admin_level, ';
259 $sSQL .= ' rank_search, ';
260 $sSQL .= ' rank_address, ';
261 $sSQL .= ' housenumber,';
262 $sSQL .= ' country_code, ';
263 $sSQL .= ' importance, ';
264 if (!$this->bDeDupe) {
265 $sSQL .= 'place_id,';
267 if (!$this->bAddressDetails) {
268 $sSQL .= 'langaddress, ';
270 $sSQL .= ' placename, ';
272 if ($this->bExtraTags) {
273 $sSQL .= 'extratags, ';
275 if ($this->bNameDetails) {
278 $sSQL .= ' extra_place ';
280 $aSubSelects[] = $sSQL;
284 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
286 Debug::printVar('Ids from location_postcode', $sPlaceIDs);
288 $sSQL .= " 'P' as osm_type,";
289 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,';
290 $sSQL .= " 'place' as class, 'postcode' as type,";
291 $sSQL .= ' null::smallint as admin_level, rank_search, rank_address,';
292 $sSQL .= ' place_id, parent_place_id,';
293 $sSQL .= ' -1 as housenumber,';
294 $sSQL .= ' country_code,';
295 $sSQL .= $this->langAddressSql('-1');
296 $sSQL .= ' postcode as placename,';
297 $sSQL .= ' postcode as ref,';
298 if ($this->bExtraTags) {
299 $sSQL .= 'null::text AS extra,';
301 if ($this->bNameDetails) {
302 $sSQL .= 'null::text AS names,';
304 $sSQL .= ' ST_x(geometry) AS lon, ST_y(geometry) AS lat,';
305 $sSQL .= ' (0.75-(rank_search::float/40)) AS importance, ';
306 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
307 $sSQL .= ' null::text AS extra_place ';
308 $sSQL .= 'FROM location_postcode lp';
309 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
310 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
312 $aSubSelects[] = $sSQL;
315 // All other tables are rank 30 only.
316 if ($iMaxRank == 30) {
318 if (CONST_Use_US_Tiger_Data) {
319 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
321 Debug::printVar('Ids from Tiger table', $sPlaceIDs);
322 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
323 // Tiger search only if a housenumber was searched and if it was found
324 // (realized through a join)
326 $sSQL .= " 'T' AS osm_type, ";
327 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ';
328 $sSQL .= " 'place' AS class, ";
329 $sSQL .= " 'house' AS type, ";
330 $sSQL .= ' null::smallint AS admin_level, ';
331 $sSQL .= ' 30 AS rank_search, ';
332 $sSQL .= ' 30 AS rank_address, ';
333 $sSQL .= ' place_id, ';
334 $sSQL .= ' parent_place_id, ';
335 $sSQL .= ' housenumber_for_place as housenumber,';
336 $sSQL .= " 'us' AS country_code, ";
337 $sSQL .= $this->langAddressSql('housenumber_for_place');
338 $sSQL .= ' null::text AS placename, ';
339 $sSQL .= ' null::text AS ref, ';
340 if ($this->bExtraTags) {
341 $sSQL .= 'null::text AS extra,';
343 if ($this->bNameDetails) {
344 $sSQL .= 'null::text AS names,';
346 $sSQL .= ' st_x(centroid) AS lon, ';
347 $sSQL .= ' st_y(centroid) AS lat,';
348 $sSQL .= ' -1.15 AS importance, ';
349 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
350 $sSQL .= ' null::text AS extra_place ';
352 $sSQL .= ' SELECT place_id, '; // interpolate the Tiger housenumbers here
353 $sSQL .= ' CASE WHEN startnumber != endnumber';
354 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float)';
355 $sSQL .= ' ELSE ST_LineInterpolatePoint(linegeo, 0.5) END AS centroid, ';
356 $sSQL .= ' parent_place_id, ';
357 $sSQL .= ' housenumber_for_place';
359 $sSQL .= ' location_property_tiger ';
360 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
362 $sSQL .= ' housenumber_for_place >= startnumber';
363 $sSQL .= ' AND housenumber_for_place <= endnumber';
364 $sSQL .= ' ) AS blub'; //postgres wants an alias here
366 $aSubSelects[] = $sSQL;
370 // osmline - interpolated housenumbers
371 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
373 Debug::printVar('Ids from interpolation', $sPlaceIDs);
374 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
375 // interpolation line search only if a housenumber was searched
376 // (realized through a join)
378 $sSQL .= " 'W' AS osm_type, ";
379 $sSQL .= ' osm_id, ';
380 $sSQL .= " 'place' AS class, ";
381 $sSQL .= " 'house' AS type, ";
382 $sSQL .= ' null::smallint AS admin_level, ';
383 $sSQL .= ' 30 AS rank_search, ';
384 $sSQL .= ' 30 AS rank_address, ';
385 $sSQL .= ' place_id, ';
386 $sSQL .= ' parent_place_id, ';
387 $sSQL .= ' housenumber_for_place as housenumber,';
388 $sSQL .= ' country_code, ';
389 $sSQL .= $this->langAddressSql('housenumber_for_place');
390 $sSQL .= ' null::text AS placename, ';
391 $sSQL .= ' null::text AS ref, ';
392 if ($this->bExtraTags) {
393 $sSQL .= 'null::text AS extra, ';
395 if ($this->bNameDetails) {
396 $sSQL .= 'null::text AS names, ';
398 $sSQL .= ' st_x(centroid) AS lon, ';
399 $sSQL .= ' st_y(centroid) AS lat, ';
400 // slightly smaller than the importance for normal houses
401 $sSQL .= ' -0.1 AS importance, ';
402 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
403 $sSQL .= ' null::text AS extra_place ';
406 $sSQL .= ' osm_id, ';
407 $sSQL .= ' place_id, ';
408 $sSQL .= ' country_code, ';
409 $sSQL .= ' CASE '; // interpolate the housenumbers here
410 $sSQL .= ' WHEN startnumber != endnumber ';
411 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ';
412 $sSQL .= ' ELSE linegeo ';
413 $sSQL .= ' END as centroid, ';
414 $sSQL .= ' parent_place_id, ';
415 $sSQL .= ' housenumber_for_place ';
417 $sSQL .= ' location_property_osmline ';
418 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
420 $sSQL .= ' WHERE housenumber_for_place >= 0 ';
421 $sSQL .= ' ) as blub'; //postgres wants an alias here
423 $aSubSelects[] = $sSQL;
427 if (empty($aSubSelects)) {
431 $sSQL = join(' UNION ', $aSubSelects);
432 Debug::printSQL($sSQL);
433 $aPlaces = $this->oDB->getAll($sSQL, null, 'Could not lookup place');
435 foreach ($aPlaces as &$aPlace) {
436 $aPlace['importance'] = (float) $aPlace['importance'];
437 if ($this->bAddressDetails) {
438 // to get addressdetails for tiger data, the housenumber is needed
439 $aPlace['address'] = new AddressDetails(
442 $aPlace['housenumber'],
443 $this->aLangPrefOrderSql
445 $aPlace['langaddress'] = $aPlace['address']->getLocaleAddress();
448 if ($this->bExtraTags) {
449 if ($aPlace['extra']) {
450 $aPlace['sExtraTags'] = json_decode($aPlace['extra'], true);
452 $aPlace['sExtraTags'] = (object) array();
456 if ($this->bNameDetails) {
457 $aPlace['sNameDetails'] = $this->extractNames($aPlace['names']);
460 $aPlace['addresstype'] = ClassTypes\getLabelTag(
462 $aPlace['country_code']
465 $aResults[$aPlace['place_id']] = $aPlace;
468 $aResults = array_filter(
471 return !($v instanceof Result);
475 Debug::printVar('Places', $aResults);
481 private function extractNames($sNames)
484 return (object) array();
487 $aFullNames = json_decode($sNames, true);
490 foreach ($aFullNames as $sKey => $sValue) {
491 if (strpos($sKey, '_place_') === 0) {
492 $sSubKey = substr($sKey, 7);
493 if (array_key_exists($sSubKey, $aFullNames)) {
494 $aNames[$sKey] = $sValue;
496 $aNames[$sSubKey] = $sValue;
499 $aNames[$sKey] = $sValue;
507 /* returns an array which will contain the keys
509 * and may also contain one or more of the keys
517 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
520 $aOutlineResult = array();
522 return $aOutlineResult;
525 // Get the bounding box and outline polygon
526 $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
527 $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
528 $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
529 $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
530 if ($this->bIncludePolygonAsGeoJSON) {
531 $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
533 if ($this->bIncludePolygonAsKML) {
534 $sSQL .= ',ST_AsKML(geometry) as askml';
536 if ($this->bIncludePolygonAsSVG) {
537 $sSQL .= ',ST_AsSVG(geometry) as assvg';
539 if ($this->bIncludePolygonAsText) {
540 $sSQL .= ',ST_AsText(geometry) as astext';
543 $sSQL .= ' FROM (SELECT place_id';
544 if ($fLonReverse != null && $fLatReverse != null) {
545 $sSQL .= ',CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
546 $sSQL .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
547 $sSQL .=' ELSE centroid END AS centroid';
549 $sSQL .= ',centroid';
551 if ($this->fPolygonSimplificationThreshold > 0) {
552 $sSQL .= ',ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry';
554 $sSQL .= ',geometry';
556 $sSQL .= ' FROM placex where place_id = '.$iPlaceID.') as plx';
558 $aPointPolygon = $this->oDB->getRow($sSQL, null, 'Could not get outline');
560 if ($aPointPolygon && $aPointPolygon['place_id']) {
561 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
562 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
563 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
566 if ($this->bIncludePolygonAsGeoJSON) {
567 $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
569 if ($this->bIncludePolygonAsKML) {
570 $aOutlineResult['askml'] = $aPointPolygon['askml'];
572 if ($this->bIncludePolygonAsSVG) {
573 $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
575 if ($this->bIncludePolygonAsText) {
576 $aOutlineResult['astext'] = $aPointPolygon['astext'];
579 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
580 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
581 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
584 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
585 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
586 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
589 $aOutlineResult['aBoundingBox'] = array(
590 (string)$aPointPolygon['minlat'],
591 (string)$aPointPolygon['maxlat'],
592 (string)$aPointPolygon['minlon'],
593 (string)$aPointPolygon['maxlon']
597 // as a fallback we generate a bounding box without knowing the size of the geometry
598 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
600 'minlat' => $fLat - $fRadius,
601 'maxlat' => $fLat + $fRadius,
602 'minlon' => $fLon - $fRadius,
603 'maxlon' => $fLon + $fRadius
606 $aOutlineResult['aBoundingBox'] = array(
607 (string)$aBounds['minlat'],
608 (string)$aBounds['maxlat'],
609 (string)$aBounds['minlon'],
610 (string)$aBounds['maxlon']
613 return $aOutlineResult;