5 require_once(CONST_BasePath.'/lib/Result.php');
11 protected $aLangPrefOrderSql = "''";
13 protected $bAddressDetails = false;
14 protected $bExtraTags = false;
15 protected $bNameDetails = false;
17 protected $bIncludePolygonAsPoints = 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 setAnchorSql($sPoint)
37 $this->sAnchorSql = $sPoint;
40 public function setDeDupe($bDeDupe)
42 $this->bDeDupe = $bDeDupe;
45 public function setAddressRankList($aList)
47 $this->sAddressRankListSql = '('.join(',', $aList).')';
50 public function setAllowedTypesSQLList($sSql)
52 $this->sAllowedTypesSQLList = $sSql;
55 public function setLanguagePreference($aLangPrefOrder)
57 $this->aLangPrefOrderSql =
58 'ARRAY['.join(',', array_map('getDBQuoted', $aLangPrefOrder)).']';
61 public function setIncludeAddressDetails($bAddressDetails = true)
63 $this->bAddressDetails = $bAddressDetails;
66 public function setIncludeExtraTags($bExtraTags = false)
68 $this->bExtraTags = $bExtraTags;
71 public function setIncludeNameDetails($bNameDetails = false)
73 $this->bNameDetails = $bNameDetails;
76 public function setIncludePolygonAsPoints($b = true)
78 $this->bIncludePolygonAsPoints = $b;
81 public function setIncludePolygonAsText($b = true)
83 $this->bIncludePolygonAsText = $b;
86 public function setIncludePolygonAsGeoJSON($b = true)
88 $this->bIncludePolygonAsGeoJSON = $b;
91 public function setIncludePolygonAsKML($b = true)
93 $this->bIncludePolygonAsKML = $b;
96 public function setIncludePolygonAsSVG($b = true)
98 $this->bIncludePolygonAsSVG = $b;
101 public function setPolygonSimplificationThreshold($f)
103 $this->fPolygonSimplificationThreshold = $f;
106 private function addressImportanceSql($sGeometry, $sPlaceId)
108 if ($this->sAnchorSql) {
109 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
111 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
112 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
113 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
114 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
115 $sSQL .= ' AND ai_s.isaddress ';
116 $sSQL .= ' AND ai_p.importance is not null)';
119 return $sSQL.' AS addressimportance,';
122 private function langAddressSql($sHousenumber)
124 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
127 public function lookupOSMID($sType, $iID)
129 $sSQL = "select place_id from placex where osm_type = '".$sType."' and osm_id = ".$iID;
130 $iPlaceID = chksql($this->oDB->getOne($sSQL));
136 return $this->lookup(new Result($iPlaceID));
139 public function lookup($oResult, $iMinRank = 0, $iMaxRank = 30)
141 if ($oResult === null) {
145 $aResults = array($oResult->iId => $oResult);
147 $aSubSelects = array();
149 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
150 if (CONST_Debug) var_dump('PLACEX', $sPlaceIDs);
153 $sSQL .= ' osm_type,';
157 $sSQL .= ' admin_level,';
158 $sSQL .= ' rank_search,';
159 $sSQL .= ' rank_address,';
160 $sSQL .= ' min(place_id) AS place_id,';
161 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
162 $sSQL .= ' housenumber,';
163 $sSQL .= ' country_code,';
164 $sSQL .= $this->langAddressSql('-1');
165 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
166 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
167 if ($this->bExtraTags) {
168 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
170 if ($this->bNameDetails) {
171 $sSQL .= 'hstore_to_json(name)::text AS names,';
173 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
174 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
175 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
176 $sSQL .= $this->addressImportanceSql(
178 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
180 $sSQL .= " (extratags->'place') AS extra_place ";
181 $sSQL .= ' FROM placex';
182 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
184 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
185 if (14 >= $iMinRank && 14 <= $iMaxRank) {
186 $sSQL .= " OR (extratags->'place') = 'city'";
188 if ($this->sAddressRankListSql) {
189 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
192 if ($this->sAllowedTypesSQLList) {
193 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
195 $sSQL .= ' AND linked_place_id is null ';
196 $sSQL .= ' GROUP BY ';
197 $sSQL .= ' osm_type, ';
198 $sSQL .= ' osm_id, ';
201 $sSQL .= ' admin_level, ';
202 $sSQL .= ' rank_search, ';
203 $sSQL .= ' rank_address, ';
204 $sSQL .= ' housenumber,';
205 $sSQL .= ' country_code, ';
206 $sSQL .= ' importance, ';
207 if (!$this->bDeDupe) $sSQL .= 'place_id,';
208 $sSQL .= ' langaddress, ';
209 $sSQL .= ' placename, ';
211 if ($this->bExtraTags) $sSQL .= 'extratags, ';
212 if ($this->bNameDetails) $sSQL .= 'name, ';
213 $sSQL .= " extratags->'place' ";
215 $aSubSelects[] = $sSQL;
219 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
222 $sSQL .= " 'P' as osm_type,";
223 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
224 $sSQL .= " 'place' as class, 'postcode' as type,";
225 $sSQL .= ' null as admin_level, rank_search, rank_address,';
226 $sSQL .= ' place_id, parent_place_id,';
227 $sSQL .= ' null as housenumber,';
228 $sSQL .= ' country_code,';
229 $sSQL .= $this->langAddressSql('-1');
230 $sSQL .= " postcode as placename,";
231 $sSQL .= " postcode as ref,";
232 if ($this->bExtraTags) $sSQL .= "null AS extra,";
233 if ($this->bNameDetails) $sSQL .= "null AS names,";
234 $sSQL .= " ST_x(geometry) AS lon, ST_y(geometry) AS lat,";
235 $sSQL .= " (0.75-(rank_search::float/40)) AS importance, ";
236 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
237 $sSQL .= " null AS extra_place ";
238 $sSQL .= "FROM location_postcode lp";
239 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
240 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
242 $aSubSelects[] = $sSQL;
245 // All other tables are rank 30 only.
246 if ($iMaxRank == 30) {
248 if (CONST_Use_US_Tiger_Data) {
249 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
251 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
252 // Tiger search only if a housenumber was searched and if it was found
253 // (realized through a join)
255 $sSQL .= " 'T' AS osm_type, ";
256 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ";
257 $sSQL .= " 'place' AS class, ";
258 $sSQL .= " 'house' AS type, ";
259 $sSQL .= ' null AS admin_level, ';
260 $sSQL .= ' 30 AS rank_search, ';
261 $sSQL .= ' 30 AS rank_address, ';
262 $sSQL .= ' place_id, ';
263 $sSQL .= ' parent_place_id, ';
264 $sSQL .= ' housenumber_for_place as housenumber,';
265 $sSQL .= " 'us' AS country_code, ";
266 $sSQL .= $this->langAddressSql('housenumber_for_place');
267 $sSQL .= " null AS placename, ";
268 $sSQL .= " null AS ref, ";
269 if ($this->bExtraTags) $sSQL .= "null AS extra,";
270 if ($this->bNameDetails) $sSQL .= "null AS names,";
271 $sSQL .= " st_x(centroid) AS lon, ";
272 $sSQL .= " st_y(centroid) AS lat,";
273 $sSQL .= " -1.15 AS importance, ";
274 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
275 $sSQL .= " null AS extra_place ";
277 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
278 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
279 $sSQL .= " parent_place_id, ";
280 $sSQL .= " housenumber_for_place";
282 $sSQL .= " location_property_tiger ";
283 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
285 $sSQL .= " housenumber_for_place >= startnumber";
286 $sSQL .= " AND housenumber_for_place <= endnumber";
287 $sSQL .= " ) AS blub"; //postgres wants an alias here
289 $aSubSelects[] = $sSQL;
293 // osmline - interpolated housenumbers
294 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
296 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
297 // interpolation line search only if a housenumber was searched
298 // (realized through a join)
300 $sSQL .= " 'W' AS osm_type, ";
301 $sSQL .= " osm_id, ";
302 $sSQL .= " 'place' AS class, ";
303 $sSQL .= " 'house' AS type, ";
304 $sSQL .= ' 15 AS admin_level, ';
305 $sSQL .= ' 30 AS rank_search, ';
306 $sSQL .= ' 30 AS rank_address, ';
307 $sSQL .= ' place_id, ';
308 $sSQL .= ' parent_place_id, ';
309 $sSQL .= ' housenumber_for_place as housenumber,';
310 $sSQL .= ' country_code, ';
311 $sSQL .= $this->langAddressSql('housenumber_for_place');
312 $sSQL .= ' null AS placename, ';
313 $sSQL .= ' null AS ref, ';
314 if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
315 if ($this->bNameDetails) $sSQL .= 'null AS names, ';
316 $sSQL .= ' st_x(centroid) AS lon, ';
317 $sSQL .= ' st_y(centroid) AS lat, ';
318 // slightly smaller than the importance for normal houses
319 $sSQL .= " -0.1 AS importance, ";
320 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
321 $sSQL .= " null AS extra_place ";
324 $sSQL .= " osm_id, ";
325 $sSQL .= " place_id, ";
326 $sSQL .= " country_code, ";
327 $sSQL .= " CASE "; // interpolate the housenumbers here
328 $sSQL .= " WHEN startnumber != endnumber ";
329 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
330 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
331 $sSQL .= " END as centroid, ";
332 $sSQL .= " parent_place_id, ";
333 $sSQL .= " housenumber_for_place ";
335 $sSQL .= " location_property_osmline ";
336 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
338 $sSQL .= " WHERE housenumber_for_place >= 0 ";
339 $sSQL .= " ) as blub"; //postgres wants an alias here
341 $aSubSelects[] = $sSQL;
344 if (CONST_Use_Aux_Location_data) {
345 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
347 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
349 $sSQL .= " 'L' AS osm_type, ";
350 $sSQL .= " place_id AS osm_id, ";
351 $sSQL .= " 'place' AS class,";
352 $sSQL .= " 'house' AS type, ";
353 $sSQL .= ' null AS admin_level, ';
354 $sSQL .= ' 30 AS rank_search,';
355 $sSQL .= ' 30 AS rank_address, ';
356 $sSQL .= ' place_id,';
357 $sSQL .= ' parent_place_id, ';
358 $sSQL .= ' housenumber,';
359 $sSQL .= " 'us' AS country_code, ";
360 $sSQL .= $this->langAddressSql('-1');
361 $sSQL .= " null AS placename, ";
362 $sSQL .= " null AS ref, ";
363 if ($this->bExtraTags) $sSQL .= "null AS extra, ";
364 if ($this->bNameDetails) $sSQL .= "null AS names, ";
365 $sSQL .= " ST_X(centroid) AS lon, ";
366 $sSQL .= " ST_Y(centroid) AS lat, ";
367 $sSQL .= " -1.10 AS importance, ";
368 $sSQL .= $this->addressImportanceSql(
370 'location_property_aux.parent_place_id'
372 $sSQL .= " null AS extra_place ";
373 $sSQL .= " FROM location_property_aux ";
374 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
376 $aSubSelects[] = $sSQL;
381 if (CONST_Debug) var_dump($aSubSelects);
383 if (!sizeof($aSubSelects)) {
388 $this->oDB->getAll(join(' UNION ', $aSubSelects)),
389 "Could not lookup place"
392 if (!sizeof($aPlaces)) {
396 if (CONST_Debug) var_dump($aPlaces);
398 foreach ($aPlaces as &$aPlace) {
399 if ($this->bAddressDetails) {
400 // to get addressdetails for tiger data, the housenumber is needed
401 $aPlace['aAddress'] = $this->getAddressNames(
403 $aPlace['housenumber']
407 if ($this->bExtraTags) {
408 if ($aPlace['extra']) {
409 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
411 $aPlace['sExtraTags'] = (object) array();
415 if ($this->bNameDetails) {
416 if ($aPlace['names']) {
417 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
419 $aPlace['sNameDetails'] = (object) array();
423 $aClassType = getClassTypes();
425 $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
426 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) {
427 $sAddressType = $aClassType[$aClassType]['simplelabel'];
429 $sClassType = $aPlace['class'].':'.$aPlace['type'];
430 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
431 $sAddressType = $aClassType[$sClassType]['simplelabel'];
432 else $sAddressType = $aPlace['class'];
435 $aPlace['addresstype'] = $sAddressType;
438 if (CONST_Debug) var_dump($aPlaces);
440 return reset($aPlaces);
443 private function getAddressDetails($iPlaceID, $bAll, $sHousenumber)
446 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') as localname';
447 $sSQL .= ' FROM get_addressdata('.$iPlaceID.','.$sHousenumber.')';
449 $sSQL .= " WHERE isaddress OR type = 'country_code'";
451 $sSQL .= ' ORDER BY rank_address desc,isaddress DESC';
453 return chksql($this->oDB->getAll($sSQL));
456 public function getAddressNames($iPlaceID, $sHousenumber = null)
458 $aAddressLines = $this->getAddressDetails(
461 $sHousenumber === null ? -1 : $sHousenumber
465 $aFallback = array();
466 $aClassType = getClassTypes();
467 foreach ($aAddressLines as $aLine) {
470 if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
471 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
472 } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
473 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
474 } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
475 $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
478 $aTypeLabel = array('simplelabel' => 'address'.$aLine['rank_address']);
481 if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
482 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
483 $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
484 if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
485 $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
487 $aFallback[$sTypeLabel] = $bFallback;
495 /* returns an array which will contain the keys
497 * and may also contain one or more of the keys
507 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null)
510 $aOutlineResult = array();
511 if (!$iPlaceID) return $aOutlineResult;
513 if (CONST_Search_AreaPolygons) {
514 // Get the bounding box and outline polygon
515 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
516 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
517 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
518 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
519 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
520 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
521 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
522 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
523 $sFrom = " from placex where place_id = ".$iPlaceID;
524 if ($this->fPolygonSimplificationThreshold > 0) {
525 $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
530 $aPointPolygon = chksql($this->oDB->getRow($sSQL), "Could not get outline");
532 if ($aPointPolygon['place_id']) {
533 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
534 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
535 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
538 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
539 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
540 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
541 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
542 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
545 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
546 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
547 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
550 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
551 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
552 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
555 $aOutlineResult['aBoundingBox'] = array(
556 (string)$aPointPolygon['minlat'],
557 (string)$aPointPolygon['maxlat'],
558 (string)$aPointPolygon['minlon'],
559 (string)$aPointPolygon['maxlon']
564 // as a fallback we generate a bounding box without knowing the size of the geometry
565 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
567 if ($this->bIncludePolygonAsPoints) {
568 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
569 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
573 $aBounds['minlat'] = $fLat - $fRadius;
574 $aBounds['maxlat'] = $fLat + $fRadius;
575 $aBounds['minlon'] = $fLon - $fRadius;
576 $aBounds['maxlon'] = $fLon + $fRadius;
578 $aOutlineResult['aBoundingBox'] = array(
579 (string)$aBounds['minlat'],
580 (string)$aBounds['maxlat'],
581 (string)$aBounds['minlon'],
582 (string)$aBounds['maxlon']
585 return $aOutlineResult;