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) {
93 $aParams['addressdetails'] = '1';
95 if ($this->bExtraTags) {
96 $aParams['extratags'] = '1';
98 if ($this->bNameDetails) {
99 $aParams['namedetails'] = '1';
102 if ($this->bIncludePolygonAsText) {
103 $aParams['polygon_text'] = '1';
105 if ($this->bIncludePolygonAsGeoJSON) {
106 $aParams['polygon_geojson'] = '1';
108 if ($this->bIncludePolygonAsKML) {
109 $aParams['polygon_kml'] = '1';
111 if ($this->bIncludePolygonAsSVG) {
112 $aParams['polygon_svg'] = '1';
115 if ($this->fPolygonSimplificationThreshold > 0.0) {
116 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
119 if (!$this->bDeDupe) {
120 $aParams['dedupe'] = '0';
126 public function setAnchorSql($sPoint)
128 $this->sAnchorSql = $sPoint;
131 public function setAddressRankList($aList)
133 $this->sAddressRankListSql = '('.join(',', $aList).')';
136 public function setAllowedTypesSQLList($sSql)
138 $this->sAllowedTypesSQLList = $sSql;
141 public function setLanguagePreference($aLangPrefOrder)
143 $this->aLangPrefOrderSql = $this->oDB->getArraySQL(
144 $this->oDB->getDBQuotedList($aLangPrefOrder)
148 private function addressImportanceSql($sGeometry, $sPlaceId)
150 if ($this->sAnchorSql) {
151 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
153 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
154 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
155 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
156 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
157 $sSQL .= ' AND ai_s.isaddress ';
158 $sSQL .= ' AND ai_p.importance is not null)';
161 return $sSQL.' AS addressimportance,';
164 private function langAddressSql($sHousenumber)
166 if ($this->bAddressDetails) {
167 return ''; // langaddress will be computed from address details
170 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
173 public function lookupOSMID($sType, $iID)
175 $sSQL = 'select place_id from placex where osm_type = :type and osm_id = :id';
176 $iPlaceID = $this->oDB->getOne($sSQL, array(':type' => $sType, ':id' => $iID));
182 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
184 return empty($aResults) ? null : reset($aResults);
187 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
189 Debug::newFunction('Place lookup');
191 if (empty($aResults)) {
194 $aSubSelects = array();
196 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
198 Debug::printVar('Ids from placex', $sPlaceIDs);
200 $sSQL .= ' osm_type,';
204 $sSQL .= ' admin_level,';
205 $sSQL .= ' rank_search,';
206 $sSQL .= ' rank_address,';
207 $sSQL .= ' min(place_id) AS place_id,';
208 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
209 $sSQL .= ' -1 as housenumber,';
210 $sSQL .= ' country_code,';
211 $sSQL .= $this->langAddressSql('-1');
212 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
213 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
214 if ($this->bExtraTags) {
215 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
217 if ($this->bNameDetails) {
218 $sSQL .= 'hstore_to_json(name)::text AS names,';
220 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
221 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
222 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
223 $sSQL .= $this->addressImportanceSql(
224 'ST_Collect(centroid)',
225 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
227 $sSQL .= " COALESCE(extratags->'place', extratags->'linked_place') AS extra_place ";
228 $sSQL .= ' FROM placex';
229 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
231 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
232 if (14 >= $iMinRank && 14 <= $iMaxRank) {
233 $sSQL .= " OR (extratags->'place') = 'city'";
235 if ($this->sAddressRankListSql) {
236 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
239 if ($this->sAllowedTypesSQLList) {
240 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
242 $sSQL .= ' AND linked_place_id is null ';
243 $sSQL .= ' GROUP BY ';
244 $sSQL .= ' osm_type, ';
245 $sSQL .= ' osm_id, ';
248 $sSQL .= ' admin_level, ';
249 $sSQL .= ' rank_search, ';
250 $sSQL .= ' rank_address, ';
251 $sSQL .= ' housenumber,';
252 $sSQL .= ' country_code, ';
253 $sSQL .= ' importance, ';
254 if (!$this->bDeDupe) {
255 $sSQL .= 'place_id,';
257 if (!$this->bAddressDetails) {
258 $sSQL .= 'langaddress, ';
260 $sSQL .= ' placename, ';
262 if ($this->bExtraTags) {
263 $sSQL .= 'extratags, ';
265 if ($this->bNameDetails) {
268 $sSQL .= ' extra_place ';
270 $aSubSelects[] = $sSQL;
274 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
276 Debug::printVar('Ids from location_postcode', $sPlaceIDs);
278 $sSQL .= " 'P' as osm_type,";
279 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,';
280 $sSQL .= " 'place' as class, 'postcode' as type,";
281 $sSQL .= ' null::smallint as admin_level, rank_search, rank_address,';
282 $sSQL .= ' place_id, parent_place_id,';
283 $sSQL .= ' -1 as housenumber,';
284 $sSQL .= ' country_code,';
285 $sSQL .= $this->langAddressSql('-1');
286 $sSQL .= ' postcode as placename,';
287 $sSQL .= ' postcode as ref,';
288 if ($this->bExtraTags) {
289 $sSQL .= 'null::text AS extra,';
291 if ($this->bNameDetails) {
292 $sSQL .= 'null::text AS names,';
294 $sSQL .= ' ST_x(geometry) AS lon, ST_y(geometry) AS lat,';
295 $sSQL .= ' (0.75-(rank_search::float/40)) AS importance, ';
296 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
297 $sSQL .= ' null::text AS extra_place ';
298 $sSQL .= 'FROM location_postcode lp';
299 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
300 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
302 $aSubSelects[] = $sSQL;
305 // All other tables are rank 30 only.
306 if ($iMaxRank == 30) {
308 if (CONST_Use_US_Tiger_Data) {
309 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
311 Debug::printVar('Ids from Tiger table', $sPlaceIDs);
312 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
313 // Tiger search only if a housenumber was searched and if it was found
314 // (realized through a join)
316 $sSQL .= " 'T' AS osm_type, ";
317 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ';
318 $sSQL .= " 'place' AS class, ";
319 $sSQL .= " 'house' AS type, ";
320 $sSQL .= ' null::smallint AS admin_level, ';
321 $sSQL .= ' 30 AS rank_search, ';
322 $sSQL .= ' 30 AS rank_address, ';
323 $sSQL .= ' place_id, ';
324 $sSQL .= ' parent_place_id, ';
325 $sSQL .= ' housenumber_for_place as housenumber,';
326 $sSQL .= " 'us' AS country_code, ";
327 $sSQL .= $this->langAddressSql('housenumber_for_place');
328 $sSQL .= ' null::text AS placename, ';
329 $sSQL .= ' null::text AS ref, ';
330 if ($this->bExtraTags) {
331 $sSQL .= 'null::text AS extra,';
333 if ($this->bNameDetails) {
334 $sSQL .= 'null::text AS names,';
336 $sSQL .= ' st_x(centroid) AS lon, ';
337 $sSQL .= ' st_y(centroid) AS lat,';
338 $sSQL .= ' -1.15 AS importance, ';
339 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
340 $sSQL .= ' null::text AS extra_place ';
342 $sSQL .= ' SELECT place_id, '; // interpolate the Tiger housenumbers here
343 $sSQL .= ' ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ';
344 $sSQL .= ' parent_place_id, ';
345 $sSQL .= ' housenumber_for_place';
347 $sSQL .= ' location_property_tiger ';
348 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
350 $sSQL .= ' housenumber_for_place >= startnumber';
351 $sSQL .= ' AND housenumber_for_place <= endnumber';
352 $sSQL .= ' ) AS blub'; //postgres wants an alias here
354 $aSubSelects[] = $sSQL;
358 // osmline - interpolated housenumbers
359 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
361 Debug::printVar('Ids from interpolation', $sPlaceIDs);
362 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
363 // interpolation line search only if a housenumber was searched
364 // (realized through a join)
366 $sSQL .= " 'W' AS osm_type, ";
367 $sSQL .= ' osm_id, ';
368 $sSQL .= " 'place' AS class, ";
369 $sSQL .= " 'house' AS type, ";
370 $sSQL .= ' null::smallint AS admin_level, ';
371 $sSQL .= ' 30 AS rank_search, ';
372 $sSQL .= ' 30 AS rank_address, ';
373 $sSQL .= ' place_id, ';
374 $sSQL .= ' parent_place_id, ';
375 $sSQL .= ' housenumber_for_place as housenumber,';
376 $sSQL .= ' country_code, ';
377 $sSQL .= $this->langAddressSql('housenumber_for_place');
378 $sSQL .= ' null::text AS placename, ';
379 $sSQL .= ' null::text AS ref, ';
380 if ($this->bExtraTags) {
381 $sSQL .= 'null::text AS extra, ';
383 if ($this->bNameDetails) {
384 $sSQL .= 'null::text AS names, ';
386 $sSQL .= ' st_x(centroid) AS lon, ';
387 $sSQL .= ' st_y(centroid) AS lat, ';
388 // slightly smaller than the importance for normal houses
389 $sSQL .= ' -0.1 AS importance, ';
390 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
391 $sSQL .= ' null::text AS extra_place ';
394 $sSQL .= ' osm_id, ';
395 $sSQL .= ' place_id, ';
396 $sSQL .= ' country_code, ';
397 $sSQL .= ' CASE '; // interpolate the housenumbers here
398 $sSQL .= ' WHEN startnumber != endnumber ';
399 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ';
400 $sSQL .= ' ELSE ST_LineInterpolatePoint(linegeo, 0.5) ';
401 $sSQL .= ' END as centroid, ';
402 $sSQL .= ' parent_place_id, ';
403 $sSQL .= ' housenumber_for_place ';
405 $sSQL .= ' location_property_osmline ';
406 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
408 $sSQL .= ' WHERE housenumber_for_place >= 0 ';
409 $sSQL .= ' ) as blub'; //postgres wants an alias here
411 $aSubSelects[] = $sSQL;
415 if (empty($aSubSelects)) {
419 $sSQL = join(' UNION ', $aSubSelects);
420 Debug::printSQL($sSQL);
421 $aPlaces = $this->oDB->getAll($sSQL, null, 'Could not lookup place');
423 foreach ($aPlaces as &$aPlace) {
424 $aPlace['importance'] = (float) $aPlace['importance'];
425 if ($this->bAddressDetails) {
426 // to get addressdetails for tiger data, the housenumber is needed
427 $aPlace['address'] = new AddressDetails(
430 $aPlace['housenumber'],
431 $this->aLangPrefOrderSql
433 $aPlace['langaddress'] = $aPlace['address']->getLocaleAddress();
436 if ($this->bExtraTags) {
437 if ($aPlace['extra']) {
438 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
440 $aPlace['sExtraTags'] = (object) array();
444 if ($this->bNameDetails) {
445 if ($aPlace['names']) {
446 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
448 $aPlace['sNameDetails'] = (object) array();
452 $aPlace['addresstype'] = ClassTypes\getLabelTag(
454 $aPlace['country_code']
457 $aResults[$aPlace['place_id']] = $aPlace;
460 $aResults = array_filter(
463 return !($v instanceof Result);
467 Debug::printVar('Places', $aResults);
472 /* returns an array which will contain the keys
474 * and may also contain one or more of the keys
484 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
487 $aOutlineResult = array();
489 return $aOutlineResult;
492 // Get the bounding box and outline polygon
493 $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
494 if ($fLonReverse != null && $fLatReverse != null) {
495 $sSQL .= ' ST_Y(closest_point) as centrelat,';
496 $sSQL .= ' ST_X(closest_point) as centrelon,';
498 $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
500 $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
501 $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
502 if ($this->bIncludePolygonAsGeoJSON) {
503 $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
505 if ($this->bIncludePolygonAsKML) {
506 $sSQL .= ',ST_AsKML(geometry) as askml';
508 if ($this->bIncludePolygonAsSVG) {
509 $sSQL .= ',ST_AsSVG(geometry) as assvg';
511 if ($this->bIncludePolygonAsText) {
512 $sSQL .= ',ST_AsText(geometry) as astext';
514 if ($fLonReverse != null && $fLatReverse != null) {
515 $sFrom = ' from (SELECT * , CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
516 $sFrom .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
517 $sFrom .=' ELSE centroid END AS closest_point';
518 $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
520 $sFrom = ' from placex where place_id = '.$iPlaceID;
522 if ($this->fPolygonSimplificationThreshold > 0) {
523 $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
528 $aPointPolygon = $this->oDB->getRow($sSQL, null, 'Could not get outline');
530 if ($aPointPolygon && $aPointPolygon['place_id']) {
531 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
532 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
533 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
536 if ($this->bIncludePolygonAsGeoJSON) {
537 $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
539 if ($this->bIncludePolygonAsKML) {
540 $aOutlineResult['askml'] = $aPointPolygon['askml'];
542 if ($this->bIncludePolygonAsSVG) {
543 $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
545 if ($this->bIncludePolygonAsText) {
546 $aOutlineResult['astext'] = $aPointPolygon['astext'];
549 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
550 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
551 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
554 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
555 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
556 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
559 $aOutlineResult['aBoundingBox'] = array(
560 (string)$aPointPolygon['minlat'],
561 (string)$aPointPolygon['maxlat'],
562 (string)$aPointPolygon['minlon'],
563 (string)$aPointPolygon['maxlon']
567 // as a fallback we generate a bounding box without knowing the size of the geometry
568 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
570 'minlat' => $fLat - $fRadius,
571 'maxlat' => $fLat + $fRadius,
572 'minlon' => $fLon - $fRadius,
573 'maxlon' => $fLon + $fRadius
576 $aOutlineResult['aBoundingBox'] = array(
577 (string)$aBounds['minlat'],
578 (string)$aBounds['maxlat'],
579 (string)$aBounds['minlon'],
580 (string)$aBounds['maxlon']
583 return $aOutlineResult;