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 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
138 return sizeof($aResults) ? reset($aResults) : null;
141 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
143 if (!sizeof($aResults)) {
146 $aSubSelects = array();
148 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
149 if (CONST_Debug) var_dump('PLACEX', $sPlaceIDs);
152 $sSQL .= ' osm_type,';
156 $sSQL .= ' admin_level,';
157 $sSQL .= ' rank_search,';
158 $sSQL .= ' rank_address,';
159 $sSQL .= ' min(place_id) AS place_id,';
160 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
161 $sSQL .= ' housenumber,';
162 $sSQL .= ' country_code,';
163 $sSQL .= $this->langAddressSql('-1');
164 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
165 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
166 if ($this->bExtraTags) {
167 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
169 if ($this->bNameDetails) {
170 $sSQL .= 'hstore_to_json(name)::text AS names,';
172 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
173 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
174 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
175 $sSQL .= $this->addressImportanceSql(
177 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
179 $sSQL .= " (extratags->'place') AS extra_place ";
180 $sSQL .= ' FROM placex';
181 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
183 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
184 if (14 >= $iMinRank && 14 <= $iMaxRank) {
185 $sSQL .= " OR (extratags->'place') = 'city'";
187 if ($this->sAddressRankListSql) {
188 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
191 if ($this->sAllowedTypesSQLList) {
192 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
194 $sSQL .= ' AND linked_place_id is null ';
195 $sSQL .= ' GROUP BY ';
196 $sSQL .= ' osm_type, ';
197 $sSQL .= ' osm_id, ';
200 $sSQL .= ' admin_level, ';
201 $sSQL .= ' rank_search, ';
202 $sSQL .= ' rank_address, ';
203 $sSQL .= ' housenumber,';
204 $sSQL .= ' country_code, ';
205 $sSQL .= ' importance, ';
206 if (!$this->bDeDupe) $sSQL .= 'place_id,';
207 $sSQL .= ' langaddress, ';
208 $sSQL .= ' placename, ';
210 if ($this->bExtraTags) $sSQL .= 'extratags, ';
211 if ($this->bNameDetails) $sSQL .= 'name, ';
212 $sSQL .= " extratags->'place' ";
214 $aSubSelects[] = $sSQL;
218 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
221 $sSQL .= " 'P' as osm_type,";
222 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
223 $sSQL .= " 'place' as class, 'postcode' as type,";
224 $sSQL .= ' null as admin_level, rank_search, rank_address,';
225 $sSQL .= ' place_id, parent_place_id,';
226 $sSQL .= ' null as housenumber,';
227 $sSQL .= ' country_code,';
228 $sSQL .= $this->langAddressSql('-1');
229 $sSQL .= " postcode as placename,";
230 $sSQL .= " postcode as ref,";
231 if ($this->bExtraTags) $sSQL .= "null AS extra,";
232 if ($this->bNameDetails) $sSQL .= "null AS names,";
233 $sSQL .= " ST_x(geometry) AS lon, ST_y(geometry) AS lat,";
234 $sSQL .= " (0.75-(rank_search::float/40)) AS importance, ";
235 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
236 $sSQL .= " null AS extra_place ";
237 $sSQL .= "FROM location_postcode lp";
238 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
239 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
241 $aSubSelects[] = $sSQL;
244 // All other tables are rank 30 only.
245 if ($iMaxRank == 30) {
247 if (CONST_Use_US_Tiger_Data) {
248 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
250 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
251 // Tiger search only if a housenumber was searched and if it was found
252 // (realized through a join)
254 $sSQL .= " 'T' AS osm_type, ";
255 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ";
256 $sSQL .= " 'place' AS class, ";
257 $sSQL .= " 'house' AS type, ";
258 $sSQL .= ' null AS admin_level, ';
259 $sSQL .= ' 30 AS rank_search, ';
260 $sSQL .= ' 30 AS rank_address, ';
261 $sSQL .= ' place_id, ';
262 $sSQL .= ' parent_place_id, ';
263 $sSQL .= ' housenumber_for_place as housenumber,';
264 $sSQL .= " 'us' AS country_code, ";
265 $sSQL .= $this->langAddressSql('housenumber_for_place');
266 $sSQL .= " null AS placename, ";
267 $sSQL .= " null AS ref, ";
268 if ($this->bExtraTags) $sSQL .= "null AS extra,";
269 if ($this->bNameDetails) $sSQL .= "null AS names,";
270 $sSQL .= " st_x(centroid) AS lon, ";
271 $sSQL .= " st_y(centroid) AS lat,";
272 $sSQL .= " -1.15 AS importance, ";
273 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
274 $sSQL .= " null AS extra_place ";
276 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
277 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
278 $sSQL .= " parent_place_id, ";
279 $sSQL .= " housenumber_for_place";
281 $sSQL .= " location_property_tiger ";
282 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
284 $sSQL .= " housenumber_for_place >= startnumber";
285 $sSQL .= " AND housenumber_for_place <= endnumber";
286 $sSQL .= " ) AS blub"; //postgres wants an alias here
288 $aSubSelects[] = $sSQL;
292 // osmline - interpolated housenumbers
293 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
295 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
296 // interpolation line search only if a housenumber was searched
297 // (realized through a join)
299 $sSQL .= " 'W' AS osm_type, ";
300 $sSQL .= " osm_id, ";
301 $sSQL .= " 'place' AS class, ";
302 $sSQL .= " 'house' AS type, ";
303 $sSQL .= ' 15 AS admin_level, ';
304 $sSQL .= ' 30 AS rank_search, ';
305 $sSQL .= ' 30 AS rank_address, ';
306 $sSQL .= ' place_id, ';
307 $sSQL .= ' parent_place_id, ';
308 $sSQL .= ' housenumber_for_place as housenumber,';
309 $sSQL .= ' country_code, ';
310 $sSQL .= $this->langAddressSql('housenumber_for_place');
311 $sSQL .= ' null AS placename, ';
312 $sSQL .= ' null AS ref, ';
313 if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
314 if ($this->bNameDetails) $sSQL .= 'null AS names, ';
315 $sSQL .= ' st_x(centroid) AS lon, ';
316 $sSQL .= ' st_y(centroid) AS lat, ';
317 // slightly smaller than the importance for normal houses
318 $sSQL .= " -0.1 AS importance, ";
319 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
320 $sSQL .= " null AS extra_place ";
323 $sSQL .= " osm_id, ";
324 $sSQL .= " place_id, ";
325 $sSQL .= " country_code, ";
326 $sSQL .= " CASE "; // interpolate the housenumbers here
327 $sSQL .= " WHEN startnumber != endnumber ";
328 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
329 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
330 $sSQL .= " END as centroid, ";
331 $sSQL .= " parent_place_id, ";
332 $sSQL .= " housenumber_for_place ";
334 $sSQL .= " location_property_osmline ";
335 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
337 $sSQL .= " WHERE housenumber_for_place >= 0 ";
338 $sSQL .= " ) as blub"; //postgres wants an alias here
340 $aSubSelects[] = $sSQL;
343 if (CONST_Use_Aux_Location_data) {
344 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
346 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
348 $sSQL .= " 'L' AS osm_type, ";
349 $sSQL .= " place_id AS osm_id, ";
350 $sSQL .= " 'place' AS class,";
351 $sSQL .= " 'house' AS type, ";
352 $sSQL .= ' null AS admin_level, ';
353 $sSQL .= ' 30 AS rank_search,';
354 $sSQL .= ' 30 AS rank_address, ';
355 $sSQL .= ' place_id,';
356 $sSQL .= ' parent_place_id, ';
357 $sSQL .= ' housenumber,';
358 $sSQL .= " 'us' AS country_code, ";
359 $sSQL .= $this->langAddressSql('-1');
360 $sSQL .= " null AS placename, ";
361 $sSQL .= " null AS ref, ";
362 if ($this->bExtraTags) $sSQL .= "null AS extra, ";
363 if ($this->bNameDetails) $sSQL .= "null AS names, ";
364 $sSQL .= " ST_X(centroid) AS lon, ";
365 $sSQL .= " ST_Y(centroid) AS lat, ";
366 $sSQL .= " -1.10 AS importance, ";
367 $sSQL .= $this->addressImportanceSql(
369 'location_property_aux.parent_place_id'
371 $sSQL .= " null AS extra_place ";
372 $sSQL .= " FROM location_property_aux ";
373 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
375 $aSubSelects[] = $sSQL;
380 if (CONST_Debug) var_dump($aSubSelects);
382 if (!sizeof($aSubSelects)) {
387 $this->oDB->getAll(join(' UNION ', $aSubSelects)),
388 "Could not lookup place"
391 foreach ($aPlaces as &$aPlace) {
392 if ($this->bAddressDetails) {
393 // to get addressdetails for tiger data, the housenumber is needed
394 $aPlace['aAddress'] = $this->getAddressNames(
396 $aPlace['housenumber']
400 if ($this->bExtraTags) {
401 if ($aPlace['extra']) {
402 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
404 $aPlace['sExtraTags'] = (object) array();
408 if ($this->bNameDetails) {
409 if ($aPlace['names']) {
410 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
412 $aPlace['sNameDetails'] = (object) array();
416 $aClassType = getClassTypes();
418 $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
419 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) {
420 $sAddressType = $aClassType[$aClassType]['simplelabel'];
422 $sClassType = $aPlace['class'].':'.$aPlace['type'];
423 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
424 $sAddressType = $aClassType[$sClassType]['simplelabel'];
425 else $sAddressType = $aPlace['class'];
428 $aPlace['addresstype'] = $sAddressType;
431 if (CONST_Debug) var_dump($aPlaces);
436 private function getAddressDetails($iPlaceID, $bAll, $sHousenumber)
439 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') as localname';
440 $sSQL .= ' FROM get_addressdata('.$iPlaceID.','.$sHousenumber.')';
442 $sSQL .= " WHERE isaddress OR type = 'country_code'";
444 $sSQL .= ' ORDER BY rank_address desc,isaddress DESC';
446 return chksql($this->oDB->getAll($sSQL));
449 public function getAddressNames($iPlaceID, $sHousenumber = null)
451 $aAddressLines = $this->getAddressDetails(
454 $sHousenumber === null ? -1 : $sHousenumber
458 $aFallback = array();
459 $aClassType = getClassTypes();
460 foreach ($aAddressLines as $aLine) {
463 if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
464 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
465 } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
466 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
467 } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
468 $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
471 $aTypeLabel = array('simplelabel' => 'address'.$aLine['rank_address']);
474 if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
475 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
476 $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
477 if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
478 $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
480 $aFallback[$sTypeLabel] = $bFallback;
488 /* returns an array which will contain the keys
490 * and may also contain one or more of the keys
500 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null)
503 $aOutlineResult = array();
504 if (!$iPlaceID) return $aOutlineResult;
506 if (CONST_Search_AreaPolygons) {
507 // Get the bounding box and outline polygon
508 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
509 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
510 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
511 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
512 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
513 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
514 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
515 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
516 $sFrom = " from placex where place_id = ".$iPlaceID;
517 if ($this->fPolygonSimplificationThreshold > 0) {
518 $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
523 $aPointPolygon = chksql($this->oDB->getRow($sSQL), "Could not get outline");
525 if ($aPointPolygon['place_id']) {
526 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
527 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
528 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
531 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
532 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
533 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
534 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
535 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
538 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
539 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
540 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
543 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
544 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
545 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
548 $aOutlineResult['aBoundingBox'] = array(
549 (string)$aPointPolygon['minlat'],
550 (string)$aPointPolygon['maxlat'],
551 (string)$aPointPolygon['minlon'],
552 (string)$aPointPolygon['maxlon']
557 // as a fallback we generate a bounding box without knowing the size of the geometry
558 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
560 if ($this->bIncludePolygonAsPoints) {
561 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
562 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
566 $aBounds['minlat'] = $fLat - $fRadius;
567 $aBounds['maxlat'] = $fLat + $fRadius;
568 $aBounds['minlon'] = $fLon - $fRadius;
569 $aBounds['maxlon'] = $fLon + $fRadius;
571 $aOutlineResult['aBoundingBox'] = array(
572 (string)$aBounds['minlat'],
573 (string)$aBounds['maxlat'],
574 (string)$aBounds['minlon'],
575 (string)$aBounds['maxlon']
578 return $aOutlineResult;