]> git.openstreetmap.org Git - nominatim.git/blob - lib/PlaceLookup.php
improvements for pull request
[nominatim.git] / lib / PlaceLookup.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_BasePath.'/lib/Result.php');
6
7 class PlaceLookup
8 {
9     protected $oDB;
10
11     protected $aLangPrefOrderSql = "''";
12
13     protected $bAddressDetails = false;
14     protected $bExtraTags = false;
15     protected $bNameDetails = false;
16
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;
23
24     protected $sAnchorSql = null;
25     protected $sAddressRankListSql = null;
26     protected $sAllowedTypesSQLList = null;
27     protected $bDeDupe = true;
28
29
30     public function __construct(&$oDB)
31     {
32         $this->oDB =& $oDB;
33     }
34
35     public function doDeDupe()
36     {
37         return $this->bDeDupe;
38     }
39
40     public function setIncludePolygonAsPoints($b = true)
41     {
42         $this->bIncludePolygonAsPoints = $b;
43     }
44
45     public function loadParamArray($oParams, $sGeomType = null)
46     {
47         $aLangs = $oParams->getPreferredLanguages();
48         $this->aLangPrefOrderSql =
49             'ARRAY['.join(',', array_map('getDBQuoted', $aLangs)).']';
50
51         $this->bAddressDetails = $oParams->getBool('addressdetails', true);
52         $this->bExtraTags = $oParams->getBool('extratags', false);
53         $this->bNameDetails = $oParams->getBool('namedetails', false);
54
55         $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
56
57         if ($sGeomType === null || $sGeomType == 'text') {
58             $this->bIncludePolygonAsText = $oParams->getBool('polygon_text');
59         }
60         if ($sGeomType === null || $sGeomType == 'geojson') {
61             $this->bIncludePolygonAsGeoJSON = $oParams->getBool('polygon_geojson');
62         }
63         if ($sGeomType === null || $sGeomType == 'kml') {
64             $this->bIncludePolygonAsKML = $oParams->getBool('polygon_kml');
65         }
66         if ($sGeomType === null || $sGeomType == 'svg') {
67             $this->bIncludePolygonAsSVG = $oParams->getBool('polygon_svg');
68         }
69         $this->fPolygonSimplificationThreshold
70             = $oParams->getFloat('polygon_threshold', 0.0);
71
72         $iWantedTypes =
73             ($this->bIncludePolygonAsText ? 1 : 0) +
74             ($this->bIncludePolygonAsGeoJSON ? 1 : 0) +
75             ($this->bIncludePolygonAsKML ? 1 : 0) +
76             ($this->bIncludePolygonAsSVG ? 1 : 0);
77         if ($iWantedTypes > CONST_PolygonOutput_MaximumTypes) {
78             if (CONST_PolygonOutput_MaximumTypes) {
79                 userError('Select only '.CONST_PolygonOutput_MaximumTypes.' polgyon output option');
80             } else {
81                 userError('Polygon output is disabled');
82             }
83         }
84     }
85
86     public function getMoreUrlParams()
87     {
88         $aParams = array();
89
90         if ($this->bAddressDetails) $aParams['addressdetails'] = '1';
91         if ($this->bExtraTags) $aParams['extratags'] = '1';
92         if ($this->bNameDetails) $aParams['namedetails'] = '1';
93
94         if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
95         if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
96         if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
97         if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
98         if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
99
100         if ($this->fPolygonSimplificationThreshold > 0.0) {
101             $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
102         }
103
104         if (!$this->bDeDupe) $aParams['dedupe'] = '0';
105
106         return $aParams;
107     }
108
109     public function setAnchorSql($sPoint)
110     {
111         $this->sAnchorSql = $sPoint;
112     }
113
114     public function setAddressRankList($aList)
115     {
116         $this->sAddressRankListSql = '('.join(',', $aList).')';
117     }
118
119     public function setAllowedTypesSQLList($sSql)
120     {
121         $this->sAllowedTypesSQLList = $sSql;
122     }
123
124     public function setLanguagePreference($aLangPrefOrder)
125     {
126         $this->aLangPrefOrderSql =
127             'ARRAY['.join(',', array_map('getDBQuoted', $aLangPrefOrder)).']';
128     }
129
130     public function setIncludeAddressDetails($bAddressDetails = true)
131     {
132         $this->bAddressDetails = $bAddressDetails;
133     }
134
135     private function addressImportanceSql($sGeometry, $sPlaceId)
136     {
137         if ($this->sAnchorSql) {
138             $sSQL = 'ST_Distance('.$this->sAnchorSql.','.$sGeometry.')';
139         } else {
140             $sSQL = '(SELECT max(ai_p.importance * (ai_p.rank_address + 2))';
141             $sSQL .= '   FROM place_addressline ai_s, placex ai_p';
142             $sSQL .= '   WHERE ai_s.place_id = '.$sPlaceId;
143             $sSQL .= '     AND ai_p.place_id = ai_s.address_place_id ';
144             $sSQL .= '     AND ai_s.isaddress ';
145             $sSQL .= '     AND ai_p.importance is not null)';
146         }
147
148         return $sSQL.' AS addressimportance,';
149     }
150
151     private function langAddressSql($sHousenumber)
152     {
153         return 'get_address_by_language(place_id,'.$sHousenumber.','.$this->aLangPrefOrderSql.') AS langaddress,';
154     }
155
156     public function lookupOSMID($sType, $iID)
157     {
158         $sSQL = "select place_id from placex where osm_type = '".$sType."' and osm_id = ".$iID;
159         $iPlaceID = chksql($this->oDB->getOne($sSQL));
160
161         if (!$iPlaceID) {
162             return null;
163         }
164
165         $aResults = $this->lookup(array($iPlaceID => new Result($iPlaceID)));
166
167         return empty($aResults) ? null : reset($aResults);
168     }
169
170     public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
171     {
172         Debug::newFunction('Place lookup');
173
174         if (empty($aResults)) {
175             return array();
176         }
177         $aSubSelects = array();
178
179         $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
180         if ($sPlaceIDs) {
181             Debug::printVar('Ids from placex', $sPlaceIDs);
182             $sSQL  = 'SELECT ';
183             $sSQL .= '    osm_type,';
184             $sSQL .= '    osm_id,';
185             $sSQL .= '    class,';
186             $sSQL .= '    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,';
199             }
200             if ($this->bNameDetails) {
201                 $sSQL .= 'hstore_to_json(name)::text AS names,';
202             }
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)'
209             );
210             $sSQL .= "    (extratags->'place') AS extra_place ";
211             $sSQL .= ' FROM placex';
212             $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
213             $sSQL .= '   AND (';
214             $sSQL .= "        placex.rank_address between $iMinRank and $iMaxRank ";
215             if (14 >= $iMinRank && 14 <= $iMaxRank) {
216                 $sSQL .= "    OR (extratags->'place') = 'city'";
217             }
218             if ($this->sAddressRankListSql) {
219                 $sSQL .= '    OR placex.rank_address in '.$this->sAddressRankListSql;
220             }
221             $sSQL .= '       ) ';
222             if ($this->sAllowedTypesSQLList) {
223                 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
224             }
225             $sSQL .= '    AND linked_place_id is null ';
226             $sSQL .= ' GROUP BY ';
227             $sSQL .= '     osm_type, ';
228             $sSQL .= '     osm_id, ';
229             $sSQL .= '     class, ';
230             $sSQL .= '     type, ';
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             $sSQL .= '     langaddress, ';
239             $sSQL .= '     placename, ';
240             $sSQL .= '     ref, ';
241             if ($this->bExtraTags) $sSQL .= 'extratags, ';
242             if ($this->bNameDetails) $sSQL .= 'name, ';
243             $sSQL .= "     extratags->'place' ";
244
245             $aSubSelects[] = $sSQL;
246         }
247
248         // postcode table
249         $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
250         if ($sPlaceIDs) {
251             Debug::printVar('Ids from location_postcode', $sPlaceIDs);
252             $sSQL = 'SELECT';
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 as admin_level, rank_search, rank_address,';
257             $sSQL .= '  place_id, parent_place_id,';
258             $sSQL .= '  null 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 AS extra,';
264             if ($this->bNameDetails) $sSQL .= 'null 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 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";
272
273             $aSubSelects[] = $sSQL;
274         }
275
276         // All other tables are rank 30 only.
277         if ($iMaxRank == 30) {
278             // TIGER table
279             if (CONST_Use_US_Tiger_Data) {
280                 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
281                 if ($sPlaceIDs) {
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)
286                     $sSQL = ' SELECT ';
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 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 AS placename, ';
300                     $sSQL .= '     null AS ref, ';
301                     if ($this->bExtraTags) $sSQL .= 'null AS extra,';
302                     if ($this->bNameDetails) $sSQL .= 'null 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 AS extra_place ';
308                     $sSQL .= ' FROM (';
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';
313                     $sSQL .= '     FROM (';
314                     $sSQL .= '            location_property_tiger ';
315                     $sSQL .= '            JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ';
316                     $sSQL .= '     WHERE ';
317                     $sSQL .= '         housenumber_for_place >= startnumber';
318                     $sSQL .= '         AND housenumber_for_place <= endnumber';
319                     $sSQL .= ' ) AS blub'; //postgres wants an alias here
320
321                     $aSubSelects[] = $sSQL;
322                 }
323             }
324
325             // osmline - interpolated housenumbers
326             $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
327             if ($sPlaceIDs) {
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)
332                 $sSQL = 'SELECT ';
333                 $sSQL .= "  'W' AS osm_type, ";
334                 $sSQL .= '  osm_id, ';
335                 $sSQL .= "  'place' AS class, ";
336                 $sSQL .= "  'house' AS type, ";
337                 $sSQL .= '  15 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 AS placename, ';
346                 $sSQL .= '  null AS ref, ';
347                 if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
348                 if ($this->bNameDetails) $sSQL .= 'null 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 AS extra_place ';
355                 $sSQL .= '  FROM (';
356                 $sSQL .= '     SELECT ';
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 ';
367                 $sSQL .= '     FROM (';
368                 $sSQL .= '            location_property_osmline ';
369                 $sSQL .= '            JOIN (values '.$sHousenumbers.') AS housenumbers(place_id, housenumber_for_place) USING(place_id)';
370                 $sSQL .= '          ) ';
371                 $sSQL .= '     WHERE housenumber_for_place >= 0 ';
372                 $sSQL .= '  ) as blub'; //postgres wants an alias here
373
374                 $aSubSelects[] = $sSQL;
375             }
376
377             if (CONST_Use_Aux_Location_data) {
378                 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
379                 if ($sPlaceIDs) {
380                     $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
381                     $sSQL = '  SELECT ';
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 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 AS placename, ';
395                     $sSQL .= '     null AS ref, ';
396                     if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
397                     if ($this->bNameDetails) $sSQL .= 'null 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(
402                         'centroid',
403                         'location_property_aux.parent_place_id'
404                     );
405                     $sSQL .= '     null AS extra_place ';
406                     $sSQL .= '  FROM location_property_aux ';
407                     $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
408
409                     $aSubSelects[] = $sSQL;
410                 }
411             }
412         }
413
414         if (empty($aSubSelects)) {
415             return array();
416         }
417
418         $sSQL = join(' UNION ', $aSubSelects);
419         Debug::printSQL($sSQL);
420         $aPlaces = chksql($this->oDB->getAll($sSQL), 'Could not lookup place');
421
422         $aClassType = getClassTypes();
423         foreach ($aPlaces as &$aPlace) {
424             if ($this->bAddressDetails) {
425                 // to get addressdetails for tiger data, the housenumber is needed
426                 $aPlace['aAddress'] = $this->getAddressNames(
427                     $aPlace['place_id'],
428                     $aPlace['housenumber']
429                 );
430             }
431
432             if ($this->bExtraTags) {
433                 if ($aPlace['extra']) {
434                     $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
435                 } else {
436                     $aPlace['sExtraTags'] = (object) array();
437                 }
438             }
439
440             if ($this->bNameDetails) {
441                 if ($aPlace['names']) {
442                     $aPlace['sNameDetails'] = json_decode($aPlace['names']);
443                 } else {
444                     $aPlace['sNameDetails'] = (object) array();
445                 }
446             }
447
448             $sAddressType = '';
449             $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
450             if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) {
451                 $sAddressType = $aClassType[$aClassType]['simplelabel'];
452             } else {
453                 $sClassType = $aPlace['class'].':'.$aPlace['type'];
454                 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
455                     $sAddressType = $aClassType[$sClassType]['simplelabel'];
456                 else $sAddressType = $aPlace['class'];
457             }
458
459             $aPlace['addresstype'] = $sAddressType;
460         }
461
462         Debug::printVar('Places', $aPlaces);
463
464         return $aPlaces;
465     }
466
467     public function getAddressDetails($iPlaceID, $bAll = false, $sHousenumber = -1)
468     {
469         $sSQL = 'SELECT *,';
470         $sSQL .= '  get_name_by_language(name,'.$this->aLangPrefOrderSql.') as localname';
471         $sSQL .= ' FROM get_addressdata('.$iPlaceID.','.$sHousenumber.')';
472         if (!$bAll) {
473             $sSQL .= " WHERE isaddress OR type = 'country_code'";
474         }
475         $sSQL .= ' ORDER BY rank_address desc,isaddress DESC';
476
477         return chksql($this->oDB->getAll($sSQL));
478     }
479
480     public function getAddressNames($iPlaceID, $sHousenumber = null)
481     {
482         $aAddressLines = $this->getAddressDetails(
483             $iPlaceID,
484             false,
485             $sHousenumber === null ? -1 : $sHousenumber
486         );
487
488         $aAddress = array();
489         $aFallback = array();
490         $aClassType = getClassTypes();
491         foreach ($aAddressLines as $aLine) {
492             $bFallback = false;
493             $aTypeLabel = false;
494             if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
495                 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
496             } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
497                 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
498             } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
499                 $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
500                 $bFallback = true;
501             } else {
502                 $aTypeLabel = array('simplelabel' => 'address'.$aLine['rank_address']);
503                 $bFallback = true;
504             }
505             if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
506                 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
507                 $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
508                 if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
509                     $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
510                 }
511                 $aFallback[$sTypeLabel] = $bFallback;
512             }
513         }
514         return $aAddress;
515     }
516
517
518
519     /* returns an array which will contain the keys
520      *   aBoundingBox
521      * and may also contain one or more of the keys
522      *   asgeojson
523      *   askml
524      *   assvg
525      *   astext
526      *   lat
527      *   lon
528      */
529
530
531     public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null, $fLonReverse = null, $fLatReverse = null)
532     {
533
534         $aOutlineResult = array();
535         if (!$iPlaceID) return $aOutlineResult;
536
537         if (CONST_Search_AreaPolygons) {
538             // Get the bounding box and outline polygon
539             $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
540             if ($fLonReverse != null && $fLatReverse != null) {
541                 $sSQL .= ' CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN';
542                 $sSQL .= ' ST_Y(closest_point)';
543                 $sSQL .= ' ELSE ST_Y(centroid) ';
544                 $sSQL .= ' END as centrelat, ';
545                 $sSQL .= ' CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN';
546                 $sSQL .= ' ST_X(closest_point)';
547                 $sSQL .= ' ELSE ST_X(centroid) ';
548                 $sSQL .= ' END as centrelon, ';
549             } else {
550                 $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
551             }
552             $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
553             $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
554             if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
555             if ($this->bIncludePolygonAsKML) $sSQL .= ',ST_AsKML(geometry) as askml';
556             if ($this->bIncludePolygonAsSVG) $sSQL .= ',ST_AsSVG(geometry) as assvg';
557             if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ',ST_AsText(geometry) as astext';
558             if ($fLonReverse != null && $fLatReverse != null) {
559                 $sFrom = ' from (SELECT * , ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326)) AS closest_point';
560             } else {
561                 $sFrom = ' from placex where place_id = '.$iPlaceID;
562             }
563             $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
564             if ($this->fPolygonSimplificationThreshold > 0) {
565                 $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
566             } else {
567                 $sSQL .= $sFrom;
568             }
569
570             $aPointPolygon = chksql($this->oDB->getRow($sSQL), 'Could not get outline');
571
572             if ($aPointPolygon['place_id']) {
573                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
574                     $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
575                     $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
576                 }
577
578                 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
579                 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
580                 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
581                 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
582                 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
583
584
585                 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
586                     $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
587                     $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
588                 }
589
590                 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
591                     $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
592                     $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
593                 }
594
595                 $aOutlineResult['aBoundingBox'] = array(
596                                                    (string)$aPointPolygon['minlat'],
597                                                    (string)$aPointPolygon['maxlat'],
598                                                    (string)$aPointPolygon['minlon'],
599                                                    (string)$aPointPolygon['maxlon']
600                                                   );
601             }
602         }
603
604         // as a fallback we generate a bounding box without knowing the size of the geometry
605         if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
606             //
607             if ($this->bIncludePolygonAsPoints) {
608                 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
609                 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
610             }
611
612             $aBounds = array();
613             $aBounds['minlat'] = $fLat - $fRadius;
614             $aBounds['maxlat'] = $fLat + $fRadius;
615             $aBounds['minlon'] = $fLon - $fRadius;
616             $aBounds['maxlon'] = $fLon + $fRadius;
617
618             $aOutlineResult['aBoundingBox'] = array(
619                                                (string)$aBounds['minlat'],
620                                                (string)$aBounds['maxlat'],
621                                                (string)$aBounds['minlon'],
622                                                (string)$aBounds['maxlon']
623                                               );
624         }
625         return $aOutlineResult;
626     }
627 }