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) $aParams['addressdetails'] = '1';
93 if ($this->bExtraTags) $aParams['extratags'] = '1';
94 if ($this->bNameDetails) $aParams['namedetails'] = '1';
96 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
97 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
98 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
99 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
101 if ($this->fPolygonSimplificationThreshold > 0.0) {
102 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
105 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
110 public function setAnchorSql($sPoint)
112 $this->sAnchorSql = $sPoint;
115 public function setAddressRankList($aList)
117 $this->sAddressRankListSql = '('.join(',', $aList).')';
120 public function setAllowedTypesSQLList($sSql)
122 $this->sAllowedTypesSQLList = $sSql;
125 public function setLanguagePreference($aLangPrefOrder)
127 $this->aLangPrefOrderSql = $this->oDB->getArraySQL(
128 $this->oDB->getDBQuotedList($aLangPrefOrder)
132 private function addressImportanceSql($sGeometry, $sPlaceId)
134 if ($this->sAnchorSql) {
135 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
137 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
138 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
139 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
140 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
141 $sSQL .= ' AND ai_s.isaddress ';
142 $sSQL .= ' AND ai_p.importance is not null)';
145 return $sSQL.' AS addressimportance,';
148 private function langAddressSql($sHousenumber)
150 if ($this->bAddressDetails)
151 return ''; // langaddress will be computed from address details
153 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
156 public function lookupOSMID($sType, $iID)
158 $sSQL = 'select place_id from placex where osm_type = :type and osm_id = :id';
159 $iPlaceID = $this->oDB->getOne($sSQL, array(':type' => $sType, ':id' => $iID));
165 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
167 return empty($aResults) ? null : reset($aResults);
170 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
172 Debug::newFunction('Place lookup');
174 if (empty($aResults)) {
177 $aSubSelects = array();
179 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
181 Debug::printVar('Ids from placex', $sPlaceIDs);
183 $sSQL .= ' osm_type,';
187 $sSQL .= ' admin_level,';
188 $sSQL .= ' rank_search,';
189 $sSQL .= ' rank_address,';
190 $sSQL .= ' min(place_id) AS place_id,';
191 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
192 $sSQL .= ' -1 as housenumber,';
193 $sSQL .= ' country_code,';
194 $sSQL .= $this->langAddressSql('-1');
195 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
196 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
197 if ($this->bExtraTags) {
198 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
200 if ($this->bNameDetails) {
201 $sSQL .= 'hstore_to_json(name)::text AS names,';
203 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
204 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
205 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
206 $sSQL .= $this->addressImportanceSql(
207 'ST_Collect(centroid)',
208 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
210 $sSQL .= " COALESCE(extratags->'place', extratags->'linked_place') AS extra_place ";
211 $sSQL .= ' FROM placex';
212 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
214 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
215 if (14 >= $iMinRank && 14 <= $iMaxRank) {
216 $sSQL .= " OR (extratags->'place') = 'city'";
218 if ($this->sAddressRankListSql) {
219 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
222 if ($this->sAllowedTypesSQLList) {
223 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
225 $sSQL .= ' AND linked_place_id is null ';
226 $sSQL .= ' GROUP BY ';
227 $sSQL .= ' osm_type, ';
228 $sSQL .= ' osm_id, ';
231 $sSQL .= ' admin_level, ';
232 $sSQL .= ' rank_search, ';
233 $sSQL .= ' rank_address, ';
234 $sSQL .= ' housenumber,';
235 $sSQL .= ' country_code, ';
236 $sSQL .= ' importance, ';
237 if (!$this->bDeDupe) $sSQL .= 'place_id,';
238 if (!$this->bAddressDetails) $sSQL .= 'langaddress, ';
239 $sSQL .= ' placename, ';
241 if ($this->bExtraTags) $sSQL .= 'extratags, ';
242 if ($this->bNameDetails) $sSQL .= 'name, ';
243 $sSQL .= ' extra_place ';
245 $aSubSelects[] = $sSQL;
249 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
251 Debug::printVar('Ids from location_postcode', $sPlaceIDs);
253 $sSQL .= " 'P' as osm_type,";
254 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,';
255 $sSQL .= " 'place' as class, 'postcode' as type,";
256 $sSQL .= ' null::smallint as admin_level, rank_search, rank_address,';
257 $sSQL .= ' place_id, parent_place_id,';
258 $sSQL .= ' -1 as housenumber,';
259 $sSQL .= ' country_code,';
260 $sSQL .= $this->langAddressSql('-1');
261 $sSQL .= ' postcode as placename,';
262 $sSQL .= ' postcode as ref,';
263 if ($this->bExtraTags) $sSQL .= 'null::text AS extra,';
264 if ($this->bNameDetails) $sSQL .= 'null::text AS names,';
265 $sSQL .= ' ST_x(geometry) AS lon, ST_y(geometry) AS lat,';
266 $sSQL .= ' (0.75-(rank_search::float/40)) AS importance, ';
267 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
268 $sSQL .= ' null::text AS extra_place ';
269 $sSQL .= 'FROM location_postcode lp';
270 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
271 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
273 $aSubSelects[] = $sSQL;
276 // All other tables are rank 30 only.
277 if ($iMaxRank == 30) {
279 if (CONST_Use_US_Tiger_Data) {
280 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
282 Debug::printVar('Ids from Tiger table', $sPlaceIDs);
283 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
284 // Tiger search only if a housenumber was searched and if it was found
285 // (realized through a join)
287 $sSQL .= " 'T' AS osm_type, ";
288 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ';
289 $sSQL .= " 'place' AS class, ";
290 $sSQL .= " 'house' AS type, ";
291 $sSQL .= ' null::smallint AS admin_level, ';
292 $sSQL .= ' 30 AS rank_search, ';
293 $sSQL .= ' 30 AS rank_address, ';
294 $sSQL .= ' place_id, ';
295 $sSQL .= ' parent_place_id, ';
296 $sSQL .= ' housenumber_for_place as housenumber,';
297 $sSQL .= " 'us' AS country_code, ";
298 $sSQL .= $this->langAddressSql('housenumber_for_place');
299 $sSQL .= ' null::text AS placename, ';
300 $sSQL .= ' null::text AS ref, ';
301 if ($this->bExtraTags) $sSQL .= 'null::text AS extra,';
302 if ($this->bNameDetails) $sSQL .= 'null::text AS names,';
303 $sSQL .= ' st_x(centroid) AS lon, ';
304 $sSQL .= ' st_y(centroid) AS lat,';
305 $sSQL .= ' -1.15 AS importance, ';
306 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
307 $sSQL .= ' null::text AS extra_place ';
309 $sSQL .= ' SELECT place_id, '; // interpolate the Tiger housenumbers here
310 $sSQL .= ' ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ';
311 $sSQL .= ' parent_place_id, ';
312 $sSQL .= ' housenumber_for_place';
314 $sSQL .= ' location_property_tiger ';
315 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
317 $sSQL .= ' housenumber_for_place >= startnumber';
318 $sSQL .= ' AND housenumber_for_place <= endnumber';
319 $sSQL .= ' ) AS blub'; //postgres wants an alias here
321 $aSubSelects[] = $sSQL;
325 // osmline - interpolated housenumbers
326 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
328 Debug::printVar('Ids from interpolation', $sPlaceIDs);
329 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
330 // interpolation line search only if a housenumber was searched
331 // (realized through a join)
333 $sSQL .= " 'W' AS osm_type, ";
334 $sSQL .= ' osm_id, ';
335 $sSQL .= " 'place' AS class, ";
336 $sSQL .= " 'house' AS type, ";
337 $sSQL .= ' null::smallint AS admin_level, ';
338 $sSQL .= ' 30 AS rank_search, ';
339 $sSQL .= ' 30 AS rank_address, ';
340 $sSQL .= ' place_id, ';
341 $sSQL .= ' parent_place_id, ';
342 $sSQL .= ' housenumber_for_place as housenumber,';
343 $sSQL .= ' country_code, ';
344 $sSQL .= $this->langAddressSql('housenumber_for_place');
345 $sSQL .= ' null::text AS placename, ';
346 $sSQL .= ' null::text AS ref, ';
347 if ($this->bExtraTags) $sSQL .= 'null::text AS extra, ';
348 if ($this->bNameDetails) $sSQL .= 'null::text AS names, ';
349 $sSQL .= ' st_x(centroid) AS lon, ';
350 $sSQL .= ' st_y(centroid) AS lat, ';
351 // slightly smaller than the importance for normal houses
352 $sSQL .= ' -0.1 AS importance, ';
353 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
354 $sSQL .= ' null::text AS extra_place ';
357 $sSQL .= ' osm_id, ';
358 $sSQL .= ' place_id, ';
359 $sSQL .= ' country_code, ';
360 $sSQL .= ' CASE '; // interpolate the housenumbers here
361 $sSQL .= ' WHEN startnumber != endnumber ';
362 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ';
363 $sSQL .= ' ELSE ST_LineInterpolatePoint(linegeo, 0.5) ';
364 $sSQL .= ' END as centroid, ';
365 $sSQL .= ' parent_place_id, ';
366 $sSQL .= ' housenumber_for_place ';
368 $sSQL .= ' location_property_osmline ';
369 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
371 $sSQL .= ' WHERE housenumber_for_place >= 0 ';
372 $sSQL .= ' ) as blub'; //postgres wants an alias here
374 $aSubSelects[] = $sSQL;
377 if (CONST_Use_Aux_Location_data) {
378 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
380 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
382 $sSQL .= " 'L' AS osm_type, ";
383 $sSQL .= ' place_id AS osm_id, ';
384 $sSQL .= " 'place' AS class,";
385 $sSQL .= " 'house' AS type, ";
386 $sSQL .= ' null::smallint AS admin_level, ';
387 $sSQL .= ' 30 AS rank_search,';
388 $sSQL .= ' 30 AS rank_address, ';
389 $sSQL .= ' place_id,';
390 $sSQL .= ' parent_place_id, ';
391 $sSQL .= ' housenumber,';
392 $sSQL .= " 'us' AS country_code, ";
393 $sSQL .= $this->langAddressSql('-1');
394 $sSQL .= ' null::text AS placename, ';
395 $sSQL .= ' null::text AS ref, ';
396 if ($this->bExtraTags) $sSQL .= 'null::text AS extra, ';
397 if ($this->bNameDetails) $sSQL .= 'null::text AS names, ';
398 $sSQL .= ' ST_X(centroid) AS lon, ';
399 $sSQL .= ' ST_Y(centroid) AS lat, ';
400 $sSQL .= ' -1.10 AS importance, ';
401 $sSQL .= $this->addressImportanceSql(
403 'location_property_aux.parent_place_id'
405 $sSQL .= ' null::text AS extra_place ';
406 $sSQL .= ' FROM location_property_aux ';
407 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
409 $aSubSelects[] = $sSQL;
414 if (empty($aSubSelects)) {
418 $sSQL = join(' UNION ', $aSubSelects);
419 Debug::printSQL($sSQL);
420 $aPlaces = $this->oDB->getAll($sSQL, null, 'Could not lookup place');
422 foreach ($aPlaces as &$aPlace) {
423 $aPlace['importance'] = (float) $aPlace['importance'];
424 if ($this->bAddressDetails) {
425 // to get addressdetails for tiger data, the housenumber is needed
426 $aPlace['address'] = new AddressDetails(
429 $aPlace['housenumber'],
430 $this->aLangPrefOrderSql
432 $aPlace['langaddress'] = $aPlace['address']->getLocaleAddress();
435 if ($this->bExtraTags) {
436 if ($aPlace['extra']) {
437 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
439 $aPlace['sExtraTags'] = (object) array();
443 if ($this->bNameDetails) {
444 if ($aPlace['names']) {
445 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
447 $aPlace['sNameDetails'] = (object) array();
451 $aPlace['addresstype'] = ClassTypes\getLabelTag(
453 $aPlace['country_code']
456 $aResults[$aPlace['place_id']] = $aPlace;
459 $aResults = array_filter(
462 return !($v instanceof Result);
466 Debug::printVar('Places', $aResults);
471 /* returns an array which will contain the keys
473 * and may also contain one or more of the keys
483 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
486 $aOutlineResult = array();
487 if (!$iPlaceID) return $aOutlineResult;
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) $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'];
530 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
531 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
532 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
535 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
536 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
537 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
540 $aOutlineResult['aBoundingBox'] = array(
541 (string)$aPointPolygon['minlat'],
542 (string)$aPointPolygon['maxlat'],
543 (string)$aPointPolygon['minlon'],
544 (string)$aPointPolygon['maxlon']
548 // as a fallback we generate a bounding box without knowing the size of the geometry
549 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
551 'minlat' => $fLat - $fRadius,
552 'maxlat' => $fLat + $fRadius,
553 'minlon' => $fLon - $fRadius,
554 'maxlon' => $fLon + $fRadius
557 $aOutlineResult['aBoundingBox'] = array(
558 (string)$aBounds['minlat'],
559 (string)$aBounds['maxlat'],
560 (string)$aBounds['minlon'],
561 (string)$aBounds['maxlon']
564 return $aOutlineResult;