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(',', array_map('getDBQuoted', $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 =
136 'ARRAY['.join(',', array_map('getDBQuoted', $aLangPrefOrder)).']';
139 private function addressImportanceSql($sGeometry, $sPlaceId)
141 if ($this->sAnchorSql) {
142 $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
144 $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
145 $sSQL .= ' FROM place_addressline ai_s, placex ai_p';
146 $sSQL .= ' WHERE ai_s.place_id = '.$sPlaceId;
147 $sSQL .= ' AND ai_p.place_id = ai_s.address_place_id ';
148 $sSQL .= ' AND ai_s.isaddress ';
149 $sSQL .= ' AND ai_p.importance is not null)';
152 return $sSQL.' AS addressimportance,';
155 private function langAddressSql($sHousenumber)
157 if ($this->bAddressDetails)
158 return ''; // langaddress will be computed from address details
160 return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
163 public function lookupOSMID($sType, $iID)
165 $sSQL = "select place_id from placex where osm_type = '".$sType."' and osm_id = ".$iID;
166 $iPlaceID = chksql($this->oDB->getOne($sSQL));
172 $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
174 return empty($aResults) ? null : reset($aResults);
177 public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
179 Debug::newFunction('Place lookup');
181 if (empty($aResults)) {
184 $aSubSelects = array();
186 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
188 Debug::printVar('Ids from placex', $sPlaceIDs);
190 $sSQL .= ' osm_type,';
194 $sSQL .= ' admin_level,';
195 $sSQL .= ' rank_search,';
196 $sSQL .= ' rank_address,';
197 $sSQL .= ' min(place_id) AS place_id,';
198 $sSQL .= ' min(parent_place_id) AS parent_place_id,';
199 $sSQL .= ' -1 as housenumber,';
200 $sSQL .= ' country_code,';
201 $sSQL .= $this->langAddressSql('-1');
202 $sSQL .= ' get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
203 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
204 if ($this->bExtraTags) {
205 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
207 if ($this->bNameDetails) {
208 $sSQL .= 'hstore_to_json(name)::text AS names,';
210 $sSQL .= ' avg(ST_X(centroid)) AS lon, ';
211 $sSQL .= ' avg(ST_Y(centroid)) AS lat, ';
212 $sSQL .= ' COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
213 $sSQL .= $this->addressImportanceSql(
214 'ST_Collect(centroid)',
215 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
217 $sSQL .= " (extratags->'place') AS extra_place ";
218 $sSQL .= ' FROM placex';
219 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
221 $sSQL .= " placex.rank_address between $iMinRank and $iMaxRank ";
222 if (14 >= $iMinRank && 14 <= $iMaxRank) {
223 $sSQL .= " OR (extratags->'place') = 'city'";
225 if ($this->sAddressRankListSql) {
226 $sSQL .= ' OR placex.rank_address in '.$this->sAddressRankListSql;
229 if ($this->sAllowedTypesSQLList) {
230 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
232 $sSQL .= ' AND linked_place_id is null ';
233 $sSQL .= ' GROUP BY ';
234 $sSQL .= ' osm_type, ';
235 $sSQL .= ' osm_id, ';
238 $sSQL .= ' admin_level, ';
239 $sSQL .= ' rank_search, ';
240 $sSQL .= ' rank_address, ';
241 $sSQL .= ' housenumber,';
242 $sSQL .= ' country_code, ';
243 $sSQL .= ' importance, ';
244 if (!$this->bDeDupe) $sSQL .= 'place_id,';
245 if (!$this->bAddressDetails) $sSQL .= 'langaddress, ';
246 $sSQL .= ' placename, ';
248 if ($this->bExtraTags) $sSQL .= 'extratags, ';
249 if ($this->bNameDetails) $sSQL .= 'name, ';
250 $sSQL .= " extratags->'place' ";
252 $aSubSelects[] = $sSQL;
256 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
258 Debug::printVar('Ids from location_postcode', $sPlaceIDs);
260 $sSQL .= " 'P' as osm_type,";
261 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,';
262 $sSQL .= " 'place' as class, 'postcode' as type,";
263 $sSQL .= ' null as admin_level, rank_search, rank_address,';
264 $sSQL .= ' place_id, parent_place_id,';
265 $sSQL .= ' null as housenumber,';
266 $sSQL .= ' country_code,';
267 $sSQL .= $this->langAddressSql('-1');
268 $sSQL .= ' postcode as placename,';
269 $sSQL .= ' postcode as ref,';
270 if ($this->bExtraTags) $sSQL .= 'null AS extra,';
271 if ($this->bNameDetails) $sSQL .= 'null AS names,';
272 $sSQL .= ' ST_x(geometry) AS lon, ST_y(geometry) AS lat,';
273 $sSQL .= ' (0.75-(rank_search::float/40)) AS importance, ';
274 $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
275 $sSQL .= ' null AS extra_place ';
276 $sSQL .= 'FROM location_postcode lp';
277 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
278 $sSQL .= " AND lp.rank_address between $iMinRank and $iMaxRank";
280 $aSubSelects[] = $sSQL;
283 // All other tables are rank 30 only.
284 if ($iMaxRank == 30) {
286 if (CONST_Use_US_Tiger_Data) {
287 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
289 Debug::printVar('Ids from Tiger table', $sPlaceIDs);
290 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
291 // Tiger search only if a housenumber was searched and if it was found
292 // (realized through a join)
294 $sSQL .= " 'T' AS osm_type, ";
295 $sSQL .= ' (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ';
296 $sSQL .= " 'place' AS class, ";
297 $sSQL .= " 'house' AS type, ";
298 $sSQL .= ' null AS admin_level, ';
299 $sSQL .= ' 30 AS rank_search, ';
300 $sSQL .= ' 30 AS rank_address, ';
301 $sSQL .= ' place_id, ';
302 $sSQL .= ' parent_place_id, ';
303 $sSQL .= ' housenumber_for_place as housenumber,';
304 $sSQL .= " 'us' AS country_code, ";
305 $sSQL .= $this->langAddressSql('housenumber_for_place');
306 $sSQL .= ' null AS placename, ';
307 $sSQL .= ' null AS ref, ';
308 if ($this->bExtraTags) $sSQL .= 'null AS extra,';
309 if ($this->bNameDetails) $sSQL .= 'null AS names,';
310 $sSQL .= ' st_x(centroid) AS lon, ';
311 $sSQL .= ' st_y(centroid) AS lat,';
312 $sSQL .= ' -1.15 AS importance, ';
313 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
314 $sSQL .= ' null AS extra_place ';
316 $sSQL .= ' SELECT place_id, '; // interpolate the Tiger housenumbers here
317 $sSQL .= ' ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ';
318 $sSQL .= ' parent_place_id, ';
319 $sSQL .= ' housenumber_for_place';
321 $sSQL .= ' location_property_tiger ';
322 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
324 $sSQL .= ' housenumber_for_place >= startnumber';
325 $sSQL .= ' AND housenumber_for_place <= endnumber';
326 $sSQL .= ' ) AS blub'; //postgres wants an alias here
328 $aSubSelects[] = $sSQL;
332 // osmline - interpolated housenumbers
333 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
335 Debug::printVar('Ids from interpolation', $sPlaceIDs);
336 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
337 // interpolation line search only if a housenumber was searched
338 // (realized through a join)
340 $sSQL .= " 'W' AS osm_type, ";
341 $sSQL .= ' osm_id, ';
342 $sSQL .= " 'place' AS class, ";
343 $sSQL .= " 'house' AS type, ";
344 $sSQL .= ' 15 AS admin_level, ';
345 $sSQL .= ' 30 AS rank_search, ';
346 $sSQL .= ' 30 AS rank_address, ';
347 $sSQL .= ' place_id, ';
348 $sSQL .= ' parent_place_id, ';
349 $sSQL .= ' housenumber_for_place as housenumber,';
350 $sSQL .= ' country_code, ';
351 $sSQL .= $this->langAddressSql('housenumber_for_place');
352 $sSQL .= ' null AS placename, ';
353 $sSQL .= ' null AS ref, ';
354 if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
355 if ($this->bNameDetails) $sSQL .= 'null AS names, ';
356 $sSQL .= ' st_x(centroid) AS lon, ';
357 $sSQL .= ' st_y(centroid) AS lat, ';
358 // slightly smaller than the importance for normal houses
359 $sSQL .= ' -0.1 AS importance, ';
360 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
361 $sSQL .= ' null AS extra_place ';
364 $sSQL .= ' osm_id, ';
365 $sSQL .= ' place_id, ';
366 $sSQL .= ' country_code, ';
367 $sSQL .= ' CASE '; // interpolate the housenumbers here
368 $sSQL .= ' WHEN startnumber != endnumber ';
369 $sSQL .= ' THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ';
370 $sSQL .= ' ELSE ST_LineInterpolatePoint(linegeo, 0.5) ';
371 $sSQL .= ' END as centroid, ';
372 $sSQL .= ' parent_place_id, ';
373 $sSQL .= ' housenumber_for_place ';
375 $sSQL .= ' location_property_osmline ';
376 $sSQL .= ' JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
378 $sSQL .= ' WHERE housenumber_for_place >= 0 ';
379 $sSQL .= ' ) as blub'; //postgres wants an alias here
381 $aSubSelects[] = $sSQL;
384 if (CONST_Use_Aux_Location_data) {
385 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
387 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
389 $sSQL .= " 'L' AS osm_type, ";
390 $sSQL .= ' place_id AS osm_id, ';
391 $sSQL .= " 'place' AS class,";
392 $sSQL .= " 'house' AS type, ";
393 $sSQL .= ' null AS admin_level, ';
394 $sSQL .= ' 30 AS rank_search,';
395 $sSQL .= ' 30 AS rank_address, ';
396 $sSQL .= ' place_id,';
397 $sSQL .= ' parent_place_id, ';
398 $sSQL .= ' housenumber,';
399 $sSQL .= " 'us' AS country_code, ";
400 $sSQL .= $this->langAddressSql('-1');
401 $sSQL .= ' null AS placename, ';
402 $sSQL .= ' null AS ref, ';
403 if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
404 if ($this->bNameDetails) $sSQL .= 'null AS names, ';
405 $sSQL .= ' ST_X(centroid) AS lon, ';
406 $sSQL .= ' ST_Y(centroid) AS lat, ';
407 $sSQL .= ' -1.10 AS importance, ';
408 $sSQL .= $this->addressImportanceSql(
410 'location_property_aux.parent_place_id'
412 $sSQL .= ' null AS extra_place ';
413 $sSQL .= ' FROM location_property_aux ';
414 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
416 $aSubSelects[] = $sSQL;
421 if (empty($aSubSelects)) {
425 $sSQL = join(' UNION ', $aSubSelects);
426 Debug::printSQL($sSQL);
427 $aPlaces = chksql($this->oDB->getAll($sSQL), 'Could not lookup place');
429 foreach ($aPlaces as &$aPlace) {
430 if ($this->bAddressDetails) {
431 // to get addressdetails for tiger data, the housenumber is needed
432 $aPlace['address'] = new AddressDetails(
435 $aPlace['housenumber'],
436 $this->aLangPrefOrderSql
438 $aPlace['langaddress'] = $aPlace['address']->getLocaleAddress();
441 if ($this->bExtraTags) {
442 if ($aPlace['extra']) {
443 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
445 $aPlace['sExtraTags'] = (object) array();
449 if ($this->bNameDetails) {
450 if ($aPlace['names']) {
451 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
453 $aPlace['sNameDetails'] = (object) array();
457 $aPlace['addresstype'] = ClassTypes\getProperty(
464 Debug::printVar('Places', $aPlaces);
469 /* returns an array which will contain the keys
471 * and may also contain one or more of the keys
481 public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
484 $aOutlineResult = array();
485 if (!$iPlaceID) return $aOutlineResult;
487 if (CONST_Search_AreaPolygons) {
488 // Get the bounding box and outline polygon
489 $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
490 if ($fLonReverse != null && $fLatReverse != null) {
491 $sSQL .= ' ST_Y(closest_point) as centrelat,';
492 $sSQL .= ' ST_X(closest_point) as centrelon,';
494 $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
496 $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
497 $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
498 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
499 if ($this->bIncludePolygonAsKML) $sSQL .= ',ST_AsKML(geometry) as askml';
500 if ($this->bIncludePolygonAsSVG) $sSQL .= ',ST_AsSVG(geometry) as assvg';
501 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ',ST_AsText(geometry) as astext';
502 if ($fLonReverse != null && $fLatReverse != null) {
503 $sFrom = ' from (SELECT * , CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
504 $sFrom .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
505 $sFrom .=' ELSE centroid END AS closest_point';
506 $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
508 $sFrom = ' from placex where place_id = '.$iPlaceID;
510 if ($this->fPolygonSimplificationThreshold > 0) {
511 $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
516 $aPointPolygon = chksql($this->oDB->getRow($sSQL), 'Could not get outline');
518 if ($aPointPolygon['place_id']) {
519 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
520 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
521 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
524 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
525 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
526 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
527 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
528 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
531 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
532 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
533 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
536 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
537 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
538 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
541 $aOutlineResult['aBoundingBox'] = array(
542 (string)$aPointPolygon['minlat'],
543 (string)$aPointPolygon['maxlat'],
544 (string)$aPointPolygon['minlon'],
545 (string)$aPointPolygon['maxlon']
550 // as a fallback we generate a bounding box without knowing the size of the geometry
551 if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
553 if ($this->bIncludePolygonAsPoints) {
554 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
555 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
559 $aBounds['minlat'] = $fLat - $fRadius;
560 $aBounds['maxlat'] = $fLat + $fRadius;
561 $aBounds['minlon'] = $fLon - $fRadius;
562 $aBounds['maxlon'] = $fLon + $fRadius;
564 $aOutlineResult['aBoundingBox'] = array(
565 (string)$aBounds['minlat'],
566 (string)$aBounds['maxlat'],
567 (string)$aBounds['minlon'],
568 (string)$aBounds['maxlon']
571 return $aOutlineResult;