5 require_once(CONST_BasePath.'/lib/AddressDetails.php');
6 require_once(CONST_BasePath.'/lib/Result.php');
12 protected $aLangPrefOrderSql = "''";
14 protected $bAddressDetails = false;
15 protected $bExtraTags = false;
16 protected $bNameDetails = false;
18 protected $bIncludePolygonAsPoints = false;
19 protected $bIncludePolygonAsText = false;
20 protected $bIncludePolygonAsGeoJSON = false;
21 protected $bIncludePolygonAsKML = false;
22 protected $bIncludePolygonAsSVG = false;
23 protected $fPolygonSimplificationThreshold = 0.0;
25 protected $sAnchorSql = null;
26 protected $sAddressRankListSql = null;
27 protected $sAllowedTypesSQLList = null;
28 protected $bDeDupe = true;
31 public function __construct(&$oDB)
36 public function doDeDupe()
38 return $this->bDeDupe;
41 public function setIncludePolygonAsPoints($b = true)
43 $this->bIncludePolygonAsPoints = $b;
46 public function setIncludeAddressDetails($b)
48 $this->bAddressDetails = $b;
51 public function loadParamArray($oParams, $sGeomType = null)
53 $aLangs = $oParams->getPreferredLanguages();
54 $this->aLangPrefOrderSql =
55 'ARRAY['.join(',', $this->oDB->getDBQuotedList($aLangs)).']';
57 $this->bExtraTags = $oParams->getBool('extratags', false);
58 $this->bNameDetails = $oParams->getBool('namedetails', false);
60 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
62 if ($sGeomType === null || $sGeomType == 'geojson') {
63 $this->bIncludePolygonAsGeoJSON = $oParams->getBool('polygon_geojson');
64 $this->bIncludePolygonAsPoints = false;
67 if ($oParams->getString('format', '') !== 'geojson') {
68 if ($sGeomType === null || $sGeomType == 'text') {
69 $this->bIncludePolygonAsText = $oParams->getBool('polygon_text');
71 if ($sGeomType === null || $sGeomType == 'kml') {
72 $this->bIncludePolygonAsKML = $oParams->getBool('polygon_kml');
74 if ($sGeomType === null || $sGeomType == 'svg') {
75 $this->bIncludePolygonAsSVG = $oParams->getBool('polygon_svg');
78 $this->fPolygonSimplificationThreshold
79 = $oParams->getFloat('polygon_threshold', 0.0);
82 ($this->bIncludePolygonAsText ? 1 : 0) +
83 ($this->bIncludePolygonAsGeoJSON ? 1 : 0) +
84 ($this->bIncludePolygonAsKML ? 1 : 0) +
85 ($this->bIncludePolygonAsSVG ? 1 : 0);
86 if ($iWantedTypes > CONST_PolygonOutput_MaximumTypes) {
87 if (CONST_PolygonOutput_MaximumTypes) {
88 userError('Select only '.CONST_PolygonOutput_MaximumTypes.' polgyon output option');
90 userError('Polygon output is disabled');
95 public function getMoreUrlParams()
99 if ($this->bAddressDetails) $aParams['addressdetails'] = '1';
100 if ($this->bExtraTags) $aParams['extratags'] = '1';
101 if ($this->bNameDetails) $aParams['namedetails'] = '1';
103 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
104 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
105 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
106 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
107 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
109 if ($this->fPolygonSimplificationThreshold > 0.0) {
110 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
113 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
118 public function setAnchorSql($sPoint)
120 $this->sAnchorSql = $sPoint;
123 public function setAddressRankList($aList)
125 $this->sAddressRankListSql = '('.join(',', $aList).')';
128 public function setAllowedTypesSQLList($sSql)
130 $this->sAllowedTypesSQLList = $sSql;
133 public function setLanguagePreference($aLangPrefOrder)
135 $this->aLangPrefOrderSql = $this->oDB->getArraySQL(
136 $this->oDB->getDBQuotedList($aLangPrefOrder)
140 private function addressImportanceSql($sGeometry, $sPlaceId)
142 if ($this->sAnchorSql) {
143 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
145 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
146 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
147 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
148 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
149 $sSQL .= ' AND ai_s.isaddress ';
150 $sSQL .= ' AND ai_p.importance is not null)';
153 return $sSQL.' AS addressimportance,';
156 private function langAddressSql($sHousenumber)
158 if ($this->bAddressDetails)
159 return ''; // langaddress will be computed from address details
161 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
164 public function lookupOSMID($sType, $iID)
166 $sSQL = 'select place_id from placex where osm_type = :type and osm_id = :id';
167 $iPlaceID = $this->oDB->getOne($sSQL, array(':type' => $sType, ':id' => $iID));
173 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
175 return empty($aResults) ? null : reset($aResults);
178 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
180 Debug::newFunction('Place lookup');
182 if (empty($aResults)) {
185 $aSubSelects = array();
187 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
189 Debug::printVar('Ids from placex', $sPlaceIDs);
191 $sSQL .= ' osm_type,';
195 $sSQL .= ' admin_level,';
196 $sSQL .= ' rank_search,';
197 $sSQL .= ' rank_address,';
198 $sSQL .= ' min(place_id) AS place_id,';
199 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
200 $sSQL .= ' -1 as housenumber,';
201 $sSQL .= ' country_code,';
202 $sSQL .= $this->langAddressSql('-1');
203 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
204 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
205 if ($this->bExtraTags) {
206 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
208 if ($this->bNameDetails) {
209 $sSQL .= 'hstore_to_json(name)::text AS names,';
211 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
212 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
213 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
214 $sSQL .= $this->addressImportanceSql(
215 'ST_Collect(centroid)',
216 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
218 $sSQL .= " (extratags->'place') AS extra_place ";
219 $sSQL .= ' FROM placex';
220 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
222 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
223 if (14 >= $iMinRank && 14 <= $iMaxRank) {
224 $sSQL .= " OR (extratags->'place') = 'city'";
226 if ($this->sAddressRankListSql) {
227 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
230 if ($this->sAllowedTypesSQLList) {
231 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
233 $sSQL .= ' AND linked_place_id is null ';
234 $sSQL .= ' GROUP BY ';
235 $sSQL .= ' osm_type, ';
236 $sSQL .= ' osm_id, ';
239 $sSQL .= ' admin_level, ';
240 $sSQL .= ' rank_search, ';
241 $sSQL .= ' rank_address, ';
242 $sSQL .= ' housenumber,';
243 $sSQL .= ' country_code, ';
244 $sSQL .= ' importance, ';
245 if (!$this->bDeDupe) $sSQL .= 'place_id,';
246 if (!$this->bAddressDetails) $sSQL .= 'langaddress, ';
247 $sSQL .= ' placename, ';
249 if ($this->bExtraTags) $sSQL .= 'extratags, ';
250 if ($this->bNameDetails) $sSQL .= 'name, ';
251 $sSQL .= " extratags->'place' ";
253 $aSubSelects[] = $sSQL;
257 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
259 Debug::printVar('Ids from location_postcode', $sPlaceIDs);
261 $sSQL .= " 'P' as osm_type,";
262 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,';
263 $sSQL .= " 'place' as class, 'postcode' as type,";
264 $sSQL .= ' null::smallint as admin_level, rank_search, rank_address,';
265 $sSQL .= ' place_id, parent_place_id,';
266 $sSQL .= ' -1 as housenumber,';
267 $sSQL .= ' country_code,';
268 $sSQL .= $this->langAddressSql('-1');
269 $sSQL .= ' postcode as placename,';
270 $sSQL .= ' postcode as ref,';
271 if ($this->bExtraTags) $sSQL .= 'null::text AS extra,';
272 if ($this->bNameDetails) $sSQL .= 'null::text AS names,';
273 $sSQL .= ' ST_x(geometry) AS lon, ST_y(geometry) AS lat,';
274 $sSQL .= ' (0.75-(rank_search::float/40)) AS importance, ';
275 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
276 $sSQL .= ' null::text AS extra_place ';
277 $sSQL .= 'FROM location_postcode lp';
278 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
279 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
281 $aSubSelects[] = $sSQL;
284 // All other tables are rank 30 only.
285 if ($iMaxRank == 30) {
287 if (CONST_Use_US_Tiger_Data) {
288 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
290 Debug::printVar('Ids from Tiger table', $sPlaceIDs);
291 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
292 // Tiger search only if a housenumber was searched and if it was found
293 // (realized through a join)
295 $sSQL .= " 'T' AS osm_type, ";
296 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ';
297 $sSQL .= " 'place' AS class, ";
298 $sSQL .= " 'house' AS type, ";
299 $sSQL .= ' null::smallint AS admin_level, ';
300 $sSQL .= ' 30 AS rank_search, ';
301 $sSQL .= ' 30 AS rank_address, ';
302 $sSQL .= ' place_id, ';
303 $sSQL .= ' parent_place_id, ';
304 $sSQL .= ' housenumber_for_place as housenumber,';
305 $sSQL .= " 'us' AS country_code, ";
306 $sSQL .= $this->langAddressSql('housenumber_for_place');
307 $sSQL .= ' null::text AS placename, ';
308 $sSQL .= ' null::text AS ref, ';
309 if ($this->bExtraTags) $sSQL .= 'null::text AS extra,';
310 if ($this->bNameDetails) $sSQL .= 'null::text AS names,';
311 $sSQL .= ' st_x(centroid) AS lon, ';
312 $sSQL .= ' st_y(centroid) AS lat,';
313 $sSQL .= ' -1.15 AS importance, ';
314 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
315 $sSQL .= ' null::text AS extra_place ';
317 $sSQL .= ' SELECT place_id, '; // interpolate the Tiger housenumbers here
318 $sSQL .= ' ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ';
319 $sSQL .= ' parent_place_id, ';
320 $sSQL .= ' housenumber_for_place';
322 $sSQL .= ' location_property_tiger ';
323 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
325 $sSQL .= ' housenumber_for_place >= startnumber';
326 $sSQL .= ' AND housenumber_for_place <= endnumber';
327 $sSQL .= ' ) AS blub'; //postgres wants an alias here
329 $aSubSelects[] = $sSQL;
333 // osmline - interpolated housenumbers
334 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
336 Debug::printVar('Ids from interpolation', $sPlaceIDs);
337 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
338 // interpolation line search only if a housenumber was searched
339 // (realized through a join)
341 $sSQL .= " 'W' AS osm_type, ";
342 $sSQL .= ' osm_id, ';
343 $sSQL .= " 'place' AS class, ";
344 $sSQL .= " 'house' AS type, ";
345 $sSQL .= ' null::smallint AS admin_level, ';
346 $sSQL .= ' 30 AS rank_search, ';
347 $sSQL .= ' 30 AS rank_address, ';
348 $sSQL .= ' place_id, ';
349 $sSQL .= ' parent_place_id, ';
350 $sSQL .= ' housenumber_for_place as housenumber,';
351 $sSQL .= ' country_code, ';
352 $sSQL .= $this->langAddressSql('housenumber_for_place');
353 $sSQL .= ' null::text AS placename, ';
354 $sSQL .= ' null::text AS ref, ';
355 if ($this->bExtraTags) $sSQL .= 'null::text AS extra, ';
356 if ($this->bNameDetails) $sSQL .= 'null::text AS names, ';
357 $sSQL .= ' st_x(centroid) AS lon, ';
358 $sSQL .= ' st_y(centroid) AS lat, ';
359 // slightly smaller than the importance for normal houses
360 $sSQL .= ' -0.1 AS importance, ';
361 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
362 $sSQL .= ' null::text AS extra_place ';
365 $sSQL .= ' osm_id, ';
366 $sSQL .= ' place_id, ';
367 $sSQL .= ' country_code, ';
368 $sSQL .= ' CASE '; // interpolate the housenumbers here
369 $sSQL .= ' WHEN startnumber != endnumber ';
370 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ';
371 $sSQL .= ' ELSE ST_LineInterpolatePoint(linegeo, 0.5) ';
372 $sSQL .= ' END as centroid, ';
373 $sSQL .= ' parent_place_id, ';
374 $sSQL .= ' housenumber_for_place ';
376 $sSQL .= ' location_property_osmline ';
377 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
379 $sSQL .= ' WHERE housenumber_for_place >= 0 ';
380 $sSQL .= ' ) as blub'; //postgres wants an alias here
382 $aSubSelects[] = $sSQL;
385 if (CONST_Use_Aux_Location_data) {
386 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
388 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
390 $sSQL .= " 'L' AS osm_type, ";
391 $sSQL .= ' place_id AS osm_id, ';
392 $sSQL .= " 'place' AS class,";
393 $sSQL .= " 'house' AS type, ";
394 $sSQL .= ' null::smallint AS admin_level, ';
395 $sSQL .= ' 30 AS rank_search,';
396 $sSQL .= ' 30 AS rank_address, ';
397 $sSQL .= ' place_id,';
398 $sSQL .= ' parent_place_id, ';
399 $sSQL .= ' housenumber,';
400 $sSQL .= " 'us' AS country_code, ";
401 $sSQL .= $this->langAddressSql('-1');
402 $sSQL .= ' null::text AS placename, ';
403 $sSQL .= ' null::text AS ref, ';
404 if ($this->bExtraTags) $sSQL .= 'null::text AS extra, ';
405 if ($this->bNameDetails) $sSQL .= 'null::text AS names, ';
406 $sSQL .= ' ST_X(centroid) AS lon, ';
407 $sSQL .= ' ST_Y(centroid) AS lat, ';
408 $sSQL .= ' -1.10 AS importance, ';
409 $sSQL .= $this->addressImportanceSql(
411 'location_property_aux.parent_place_id'
413 $sSQL .= ' null::text AS extra_place ';
414 $sSQL .= ' FROM location_property_aux ';
415 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
417 $aSubSelects[] = $sSQL;
422 if (empty($aSubSelects)) {
426 $sSQL = join(' UNION ', $aSubSelects);
427 Debug::printSQL($sSQL);
428 $aPlaces = $this->oDB->getAll($sSQL, null, 'Could not lookup place');
430 foreach ($aPlaces as &$aPlace) {
431 if ($this->bAddressDetails) {
432 // to get addressdetails for tiger data, the housenumber is needed
433 $aPlace['address'] = new AddressDetails(
436 $aPlace['housenumber'],
437 $this->aLangPrefOrderSql
439 $aPlace['langaddress'] = $aPlace['address']->getLocaleAddress();
442 if ($this->bExtraTags) {
443 if ($aPlace['extra']) {
444 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
446 $aPlace['sExtraTags'] = (object) array();
450 if ($this->bNameDetails) {
451 if ($aPlace['names']) {
452 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
454 $aPlace['sNameDetails'] = (object) array();
458 $aPlace['addresstype'] = ClassTypes\getProperty(
465 Debug::printVar('Places', $aPlaces);
470 /* returns an array which will contain the keys
472 * and may also contain one or more of the keys
482 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
485 $aOutlineResult = array();
486 if (!$iPlaceID) return $aOutlineResult;
488 if (CONST_Search_AreaPolygons) {
489 // Get the bounding box and outline polygon
490 $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
491 if ($fLonReverse != null && $fLatReverse != null) {
492 $sSQL .= ' ST_Y(closest_point) as centrelat,';
493 $sSQL .= ' ST_X(closest_point) as centrelon,';
495 $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
497 $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
498 $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
499 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
500 if ($this->bIncludePolygonAsKML) $sSQL .= ',ST_AsKML(geometry) as askml';
501 if ($this->bIncludePolygonAsSVG) $sSQL .= ',ST_AsSVG(geometry) as assvg';
502 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ',ST_AsText(geometry) as astext';
503 if ($fLonReverse != null && $fLatReverse != null) {
504 $sFrom = ' from (SELECT * , CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
505 $sFrom .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
506 $sFrom .=' ELSE centroid END AS closest_point';
507 $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
509 $sFrom = ' from placex where place_id = '.$iPlaceID;
511 if ($this->fPolygonSimplificationThreshold > 0) {
512 $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
517 $aPointPolygon = $this->oDB->getRow($sSQL, null, 'Could not get outline');
519 if ($aPointPolygon && $aPointPolygon['place_id']) {
520 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
521 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
522 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
525 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
526 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
527 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
528 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
529 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
532 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
533 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
534 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
537 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
538 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
539 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
542 $aOutlineResult['aBoundingBox'] = array(
543 (string)$aPointPolygon['minlat'],
544 (string)$aPointPolygon['maxlat'],
545 (string)$aPointPolygon['minlon'],
546 (string)$aPointPolygon['maxlon']
551 // as a fallback we generate a bounding box without knowing the size of the geometry
552 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
554 if ($this->bIncludePolygonAsPoints) {
555 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
556 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
560 $aBounds['minlat'] = $fLat - $fRadius;
561 $aBounds['maxlat'] = $fLat + $fRadius;
562 $aBounds['minlon'] = $fLon - $fRadius;
563 $aBounds['maxlon'] = $fLon + $fRadius;
565 $aOutlineResult['aBoundingBox'] = array(
566 (string)$aBounds['minlat'],
567 (string)$aBounds['maxlat'],
568 (string)$aBounds['minlon'],
569 (string)$aBounds['maxlon']
572 return $aOutlineResult;