]> git.openstreetmap.org Git - nominatim.git/blob - lib/PlaceLookup.php
use PlaceLookup::loadParamArray in search and lookup
[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 sizeof($aResults) ? reset($aResults) : null;
168     }
169
170     public function lookup($aResults, $iMinRank = 0, $iMaxRank = 30)
171     {
172         if (!sizeof($aResults)) {
173             return array();
174         }
175         $aSubSelects = array();
176
177         $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
178         if (CONST_Debug) var_dump('PLACEX', $sPlaceIDs);
179         if ($sPlaceIDs) {
180             $sSQL  = 'SELECT ';
181             $sSQL .= '    osm_type,';
182             $sSQL .= '    osm_id,';
183             $sSQL .= '    class,';
184             $sSQL .= '    type,';
185             $sSQL .= '    admin_level,';
186             $sSQL .= '    rank_search,';
187             $sSQL .= '    rank_address,';
188             $sSQL .= '    min(place_id) AS place_id,';
189             $sSQL .= '    min(parent_place_id) AS parent_place_id,';
190             $sSQL .= '    housenumber,';
191             $sSQL .= '    country_code,';
192             $sSQL .= $this->langAddressSql('-1');
193             $sSQL .= '    get_name_by_language(name,'.$this->aLangPrefOrderSql.') AS placename,';
194             $sSQL .= "    get_name_by_language(name, ARRAY['ref']) AS ref,";
195             if ($this->bExtraTags) {
196                 $sSQL .= 'hstore_to_json(extratags)::text AS extra,';
197             }
198             if ($this->bNameDetails) {
199                 $sSQL .= 'hstore_to_json(name)::text AS names,';
200             }
201             $sSQL .= '    avg(ST_X(centroid)) AS lon, ';
202             $sSQL .= '    avg(ST_Y(centroid)) AS lat, ';
203             $sSQL .= '    COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ';
204             $sSQL .= $this->addressImportanceSql(
205                 'ST_Collect(centroid)',
206                 'min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)'
207             );
208             $sSQL .= "    (extratags->'place') AS extra_place ";
209             $sSQL .= ' FROM placex';
210             $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
211             $sSQL .= '   AND (';
212             $sSQL .= "        placex.rank_address between $iMinRank and $iMaxRank ";
213             if (14 >= $iMinRank && 14 <= $iMaxRank) {
214                 $sSQL .= "    OR (extratags->'place') = 'city'";
215             }
216             if ($this->sAddressRankListSql) {
217                 $sSQL .= '    OR placex.rank_address in '.$this->sAddressRankListSql;
218             }
219             $sSQL .= "       ) ";
220             if ($this->sAllowedTypesSQLList) {
221                 $sSQL .= 'AND placex.class in '.$this->sAllowedTypesSQLList;
222             }
223             $sSQL .= '    AND linked_place_id is null ';
224             $sSQL .= ' GROUP BY ';
225             $sSQL .= '     osm_type, ';
226             $sSQL .= '     osm_id, ';
227             $sSQL .= '     class, ';
228             $sSQL .= '     type, ';
229             $sSQL .= '     admin_level, ';
230             $sSQL .= '     rank_search, ';
231             $sSQL .= '     rank_address, ';
232             $sSQL .= '     housenumber,';
233             $sSQL .= '     country_code, ';
234             $sSQL .= '     importance, ';
235             if (!$this->bDeDupe) $sSQL .= 'place_id,';
236             $sSQL .= '     langaddress, ';
237             $sSQL .= '     placename, ';
238             $sSQL .= '     ref, ';
239             if ($this->bExtraTags) $sSQL .= 'extratags, ';
240             if ($this->bNameDetails) $sSQL .= 'name, ';
241             $sSQL .= "     extratags->'place' ";
242
243             $aSubSelects[] = $sSQL;
244         }
245
246         // postcode table
247         $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
248         if ($sPlaceIDs) {
249             $sSQL = 'SELECT';
250             $sSQL .= "  'P' as osm_type,";
251             $sSQL .= "  (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
252             $sSQL .= "  'place' as class, 'postcode' as type,";
253             $sSQL .= '  null as admin_level, rank_search, rank_address,';
254             $sSQL .= '  place_id, parent_place_id,';
255             $sSQL .= '  null as housenumber,';
256             $sSQL .= '  country_code,';
257             $sSQL .= $this->langAddressSql('-1');
258             $sSQL .= "  postcode as placename,";
259             $sSQL .= "  postcode as ref,";
260             if ($this->bExtraTags) $sSQL .= "null AS extra,";
261             if ($this->bNameDetails) $sSQL .= "null AS names,";
262             $sSQL .= "  ST_x(geometry) AS lon, ST_y(geometry) AS lat,";
263             $sSQL .= "  (0.75-(rank_search::float/40)) AS importance, ";
264             $sSQL .= $this->addressImportanceSql('geometry', 'lp.parent_place_id');
265             $sSQL .= "  null AS extra_place ";
266             $sSQL .= "FROM location_postcode lp";
267             $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
268             $sSQL .= "   AND lp.rank_address between $iMinRank and $iMaxRank";
269
270             $aSubSelects[] = $sSQL;
271         }
272
273         // All other tables are rank 30 only.
274         if ($iMaxRank == 30) {
275             // TIGER table
276             if (CONST_Use_US_Tiger_Data) {
277                 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
278                 if ($sPlaceIDs) {
279                     $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
280                     // Tiger search only if a housenumber was searched and if it was found
281                     // (realized through a join)
282                     $sSQL = " SELECT ";
283                     $sSQL .= "     'T' AS osm_type, ";
284                     $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=blub.parent_place_id) as osm_id, ";
285                     $sSQL .= "     'place' AS class, ";
286                     $sSQL .= "     'house' AS type, ";
287                     $sSQL .= '     null AS admin_level, ';
288                     $sSQL .= '     30 AS rank_search, ';
289                     $sSQL .= '     30 AS rank_address, ';
290                     $sSQL .= '     place_id, ';
291                     $sSQL .= '     parent_place_id, ';
292                     $sSQL .= '     housenumber_for_place as housenumber,';
293                     $sSQL .= "     'us' AS country_code, ";
294                     $sSQL .= $this->langAddressSql('housenumber_for_place');
295                     $sSQL .= "     null AS placename, ";
296                     $sSQL .= "     null AS ref, ";
297                     if ($this->bExtraTags) $sSQL .= "null AS extra,";
298                     if ($this->bNameDetails) $sSQL .= "null AS names,";
299                     $sSQL .= "     st_x(centroid) AS lon, ";
300                     $sSQL .= "     st_y(centroid) AS lat,";
301                     $sSQL .= "     -1.15 AS importance, ";
302                     $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
303                     $sSQL .= "     null AS extra_place ";
304                     $sSQL .= " FROM (";
305                     $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
306                     $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
307                     $sSQL .= "         parent_place_id, ";
308                     $sSQL .= "         housenumber_for_place";
309                     $sSQL .= "     FROM (";
310                     $sSQL .= "            location_property_tiger ";
311                     $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
312                     $sSQL .= "     WHERE ";
313                     $sSQL .= "         housenumber_for_place >= startnumber";
314                     $sSQL .= "         AND housenumber_for_place <= endnumber";
315                     $sSQL .= " ) AS blub"; //postgres wants an alias here
316
317                     $aSubSelects[] = $sSQL;
318                 }
319             }
320
321             // osmline - interpolated housenumbers
322             $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
323             if ($sPlaceIDs) {
324                 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
325                 // interpolation line search only if a housenumber was searched
326                 // (realized through a join)
327                 $sSQL = "SELECT ";
328                 $sSQL .= "  'W' AS osm_type, ";
329                 $sSQL .= "  osm_id, ";
330                 $sSQL .= "  'place' AS class, ";
331                 $sSQL .= "  'house' AS type, ";
332                 $sSQL .= '  15 AS admin_level, ';
333                 $sSQL .= '  30 AS rank_search, ';
334                 $sSQL .= '  30 AS rank_address, ';
335                 $sSQL .= '  place_id, ';
336                 $sSQL .= '  parent_place_id, ';
337                 $sSQL .= '  housenumber_for_place as housenumber,';
338                 $sSQL .= '  country_code, ';
339                 $sSQL .= $this->langAddressSql('housenumber_for_place');
340                 $sSQL .= '  null AS placename, ';
341                 $sSQL .= '  null AS ref, ';
342                 if ($this->bExtraTags) $sSQL .= 'null AS extra, ';
343                 if ($this->bNameDetails) $sSQL .= 'null AS names, ';
344                 $sSQL .= '  st_x(centroid) AS lon, ';
345                 $sSQL .= '  st_y(centroid) AS lat, ';
346                 // slightly smaller than the importance for normal houses
347                 $sSQL .= "  -0.1 AS importance, ";
348                 $sSQL .= $this->addressImportanceSql('centroid', 'blub.parent_place_id');
349                 $sSQL .= "  null AS extra_place ";
350                 $sSQL .= "  FROM (";
351                 $sSQL .= "     SELECT ";
352                 $sSQL .= "         osm_id, ";
353                 $sSQL .= "         place_id, ";
354                 $sSQL .= "         country_code, ";
355                 $sSQL .= "         CASE ";             // interpolate the housenumbers here
356                 $sSQL .= "           WHEN startnumber != endnumber ";
357                 $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
358                 $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
359                 $sSQL .= "         END as centroid, ";
360                 $sSQL .= "         parent_place_id, ";
361                 $sSQL .= "         housenumber_for_place ";
362                 $sSQL .= "     FROM (";
363                 $sSQL .= "            location_property_osmline ";
364                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
365                 $sSQL .= "          ) ";
366                 $sSQL .= "     WHERE housenumber_for_place >= 0 ";
367                 $sSQL .= "  ) as blub"; //postgres wants an alias here
368
369                 $aSubSelects[] = $sSQL;
370             }
371
372             if (CONST_Use_Aux_Location_data) {
373                 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
374                 if ($sPlaceIDs) {
375                     $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
376                     $sSQL = "  SELECT ";
377                     $sSQL .= "     'L' AS osm_type, ";
378                     $sSQL .= "     place_id AS osm_id, ";
379                     $sSQL .= "     'place' AS class,";
380                     $sSQL .= "     'house' AS type, ";
381                     $sSQL .= '     null AS admin_level, ';
382                     $sSQL .= '     30 AS rank_search,';
383                     $sSQL .= '     30 AS rank_address, ';
384                     $sSQL .= '     place_id,';
385                     $sSQL .= '     parent_place_id, ';
386                     $sSQL .= '     housenumber,';
387                     $sSQL .= "     'us' AS country_code, ";
388                     $sSQL .= $this->langAddressSql('-1');
389                     $sSQL .= "     null AS placename, ";
390                     $sSQL .= "     null AS ref, ";
391                     if ($this->bExtraTags) $sSQL .= "null AS extra, ";
392                     if ($this->bNameDetails) $sSQL .= "null AS names, ";
393                     $sSQL .= "     ST_X(centroid) AS lon, ";
394                     $sSQL .= "     ST_Y(centroid) AS lat, ";
395                     $sSQL .= "     -1.10 AS importance, ";
396                     $sSQL .= $this->addressImportanceSql(
397                         'centroid',
398                         'location_property_aux.parent_place_id'
399                     );
400                     $sSQL .= "     null AS extra_place ";
401                     $sSQL .= "  FROM location_property_aux ";
402                     $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
403
404                     $aSubSelects[] = $sSQL;
405                 }
406             }
407         }
408
409         if (CONST_Debug) var_dump($aSubSelects);
410
411         if (!sizeof($aSubSelects)) {
412             return array();
413         }
414
415         $aPlaces = chksql(
416             $this->oDB->getAll(join(' UNION ', $aSubSelects)),
417             "Could not lookup place"
418         );
419
420         $aClassType = getClassTypes();
421         foreach ($aPlaces as &$aPlace) {
422             if ($this->bAddressDetails) {
423                 // to get addressdetails for tiger data, the housenumber is needed
424                 $aPlace['aAddress'] = $this->getAddressNames(
425                     $aPlace['place_id'],
426                     $aPlace['housenumber']
427                 );
428             }
429
430             if ($this->bExtraTags) {
431                 if ($aPlace['extra']) {
432                     $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
433                 } else {
434                     $aPlace['sExtraTags'] = (object) array();
435                 }
436             }
437
438             if ($this->bNameDetails) {
439                 if ($aPlace['names']) {
440                     $aPlace['sNameDetails'] = json_decode($aPlace['names']);
441                 } else {
442                     $aPlace['sNameDetails'] = (object) array();
443                 }
444             }
445
446             $sAddressType = '';
447             $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
448             if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) {
449                 $sAddressType = $aClassType[$aClassType]['simplelabel'];
450             } else {
451                 $sClassType = $aPlace['class'].':'.$aPlace['type'];
452                 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
453                     $sAddressType = $aClassType[$sClassType]['simplelabel'];
454                 else $sAddressType = $aPlace['class'];
455             }
456
457             $aPlace['addresstype'] = $sAddressType;
458         }
459
460         if (CONST_Debug) var_dump($aPlaces);
461
462         return $aPlaces;
463     }
464
465     private function getAddressDetails($iPlaceID, $bAll, $sHousenumber)
466     {
467         $sSQL = 'SELECT *,';
468         $sSQL .= '  get_name_by_language(name,'.$this->aLangPrefOrderSql.') as localname';
469         $sSQL .= ' FROM get_addressdata('.$iPlaceID.','.$sHousenumber.')';
470         if (!$bAll) {
471             $sSQL .= " WHERE isaddress OR type = 'country_code'";
472         }
473         $sSQL .= ' ORDER BY rank_address desc,isaddress DESC';
474
475         return chksql($this->oDB->getAll($sSQL));
476     }
477
478     public function getAddressNames($iPlaceID, $sHousenumber = null)
479     {
480         $aAddressLines = $this->getAddressDetails(
481             $iPlaceID,
482             false,
483             $sHousenumber === null ? -1 : $sHousenumber
484         );
485
486         $aAddress = array();
487         $aFallback = array();
488         $aClassType = getClassTypes();
489         foreach ($aAddressLines as $aLine) {
490             $bFallback = false;
491             $aTypeLabel = false;
492             if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
493                 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
494             } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
495                 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
496             } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
497                 $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
498                 $bFallback = true;
499             } else {
500                 $aTypeLabel = array('simplelabel' => 'address'.$aLine['rank_address']);
501                 $bFallback = true;
502             }
503             if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
504                 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
505                 $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
506                 if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
507                     $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
508                 }
509                 $aFallback[$sTypeLabel] = $bFallback;
510             }
511         }
512         return $aAddress;
513     }
514
515
516
517     /* returns an array which will contain the keys
518      *   aBoundingBox
519      * and may also contain one or more of the keys
520      *   asgeojson
521      *   askml
522      *   assvg
523      *   astext
524      *   lat
525      *   lon
526      */
527
528
529     public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null)
530     {
531
532         $aOutlineResult = array();
533         if (!$iPlaceID) return $aOutlineResult;
534
535         if (CONST_Search_AreaPolygons) {
536             // Get the bounding box and outline polygon
537             $sSQL  = "select place_id,0 as numfeatures,st_area(geometry) as area,";
538             $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
539             $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
540             $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
541             if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
542             if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
543             if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
544             if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
545             $sFrom = " from placex where place_id = ".$iPlaceID;
546             if ($this->fPolygonSimplificationThreshold > 0) {
547                 $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
548             } else {
549                 $sSQL .= $sFrom;
550             }
551
552             $aPointPolygon = chksql($this->oDB->getRow($sSQL), "Could not get outline");
553
554             if ($aPointPolygon['place_id']) {
555                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
556                     $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
557                     $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
558                 }
559
560                 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
561                 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
562                 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
563                 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
564                 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
565
566
567                 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
568                     $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
569                     $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
570                 }
571
572                 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
573                     $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
574                     $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
575                 }
576
577                 $aOutlineResult['aBoundingBox'] = array(
578                                                    (string)$aPointPolygon['minlat'],
579                                                    (string)$aPointPolygon['maxlat'],
580                                                    (string)$aPointPolygon['minlon'],
581                                                    (string)$aPointPolygon['maxlon']
582                                                   );
583             }
584         }
585
586         // as a fallback we generate a bounding box without knowing the size of the geometry
587         if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
588             //
589             if ($this->bIncludePolygonAsPoints) {
590                 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
591                 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
592             }
593
594             $aBounds = array();
595             $aBounds['minlat'] = $fLat - $fRadius;
596             $aBounds['maxlat'] = $fLat + $fRadius;
597             $aBounds['minlon'] = $fLon - $fRadius;
598             $aBounds['maxlon'] = $fLon + $fRadius;
599
600             $aOutlineResult['aBoundingBox'] = array(
601                                                (string)$aBounds['minlat'],
602                                                (string)$aBounds['maxlat'],
603                                                (string)$aBounds['minlon'],
604                                                (string)$aBounds['maxlon']
605                                               );
606         }
607         return $aOutlineResult;
608     }
609 }