]> git.openstreetmap.org Git - nominatim.git/blob - lib/PlaceLookup.php
Merge pull request #424 from lonvia/cleanup-logging
[nominatim.git] / lib / PlaceLookup.php
1 <?php
2         class PlaceLookup
3         {
4                 protected $oDB;
5
6                 protected $iPlaceID;
7
8                 protected $sType = false;
9
10                 protected $fTigerFraction = -1;
11
12                 protected $aLangPrefOrder = array();
13
14                 protected $bAddressDetails = false;
15
16                 protected $bExtraTags = false;
17
18                 protected $bNameDetails = false;
19
20                 protected $bIncludePolygonAsPoints = false;
21                 protected $bIncludePolygonAsText = false;
22                 protected $bIncludePolygonAsGeoJSON = false;
23                 protected $bIncludePolygonAsKML = false;
24                 protected $bIncludePolygonAsSVG = false;
25                 protected $fPolygonSimplificationThreshold = 0.0;
26
27
28                 function PlaceLookup(&$oDB)
29                 {
30                         $this->oDB =& $oDB;
31                 }
32
33                 function setLanguagePreference($aLangPrefOrder)
34                 {
35                         $this->aLangPrefOrder = $aLangPrefOrder;
36                 }
37
38                 function setIncludeAddressDetails($bAddressDetails = true)
39                 {
40                         $this->bAddressDetails = $bAddressDetails;
41                 }
42
43                 function setIncludeExtraTags($bExtraTags = false)
44                 {
45                         $this->bExtraTags = $bExtraTags;
46                 }
47
48                 function setIncludeNameDetails($bNameDetails = false)
49                 {
50                         $this->bNameDetails = $bNameDetails;
51                 }
52
53
54                 function setIncludePolygonAsPoints($b = true)
55                 {
56                         $this->bIncludePolygonAsPoints = $b;
57                 }
58
59                 function getIncludePolygonAsPoints()
60                 {
61                         return $this->bIncludePolygonAsPoints;
62                 }
63
64                 function setIncludePolygonAsText($b = true)
65                 {
66                         $this->bIncludePolygonAsText = $b;
67                 }
68
69                 function getIncludePolygonAsText()
70                 {
71                         return $this->bIncludePolygonAsText;
72                 }
73
74                 function setIncludePolygonAsGeoJSON($b = true)
75                 {
76                         $this->bIncludePolygonAsGeoJSON = $b;
77                 }
78
79                 function setIncludePolygonAsKML($b = true)
80                 {
81                         $this->bIncludePolygonAsKML = $b;
82                 }
83
84                 function setIncludePolygonAsSVG($b = true)
85                 {
86                         $this->bIncludePolygonAsSVG = $b;
87                 }
88
89                 function setPolygonSimplificationThreshold($f)
90                 {
91                         $this->fPolygonSimplificationThreshold = $f;
92                 }
93
94
95                 function setPlaceID($iPlaceID)
96                 {
97                         $this->iPlaceID = $iPlaceID;
98                 }
99
100                 function setOSMID($sType, $iID)
101                 {
102                         $sSQL = "select place_id from placex where osm_type = '".pg_escape_string($sType)."' and osm_id = ".(int)$iID." order by type = 'postcode' asc";
103                         $this->iPlaceID = $this->oDB->getOne($sSQL);
104                 }
105
106                 function lookupPlace($details)
107                 {
108                         if (isset($details['place_id'])) $this->iPlaceID = $details['place_id'];
109                         if (isset($details['type'])) $this->sType = $details['type'];
110                         if (isset($details['osm_type']) && isset($details['osm_id']))
111                         {
112                                 $this->setOSMID($details['osm_type'], $details['osm_id']);
113                         }
114                         if (isset($details['fraction'])) $this->fTigerFraction = $details['fraction'];
115
116                         return $this->lookup();
117                 }
118
119                 function lookup()
120                 {
121                         if (!$this->iPlaceID) return null;
122
123                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
124
125                         if ($this->sType == 'tiger')
126                         {
127                                 $sSQL = "select place_id,partition, 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, housenumber, null as street, null as isin, postcode,";
128                                 $sSQL .= " 'us' as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
129                                 $sSQL .= " coalesce(null,0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, 'us' as calculated_country_code, ";
130                                 $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
131                                 $sSQL .= " null as placename,";
132                                 $sSQL .= " null as ref,";
133                                 if ($this->bExtraTags) $sSQL .= " null as extra,";
134                                 if ($this->bNameDetails) $sSQL .= " null as names,";
135                                 $sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from ";
136                                 $sSQL .= " (select *, ";
137                                 $sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$this->fTigerFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
138                                 $sSQL .= " WHEN interpolationtype='even' THEN ((".$this->fTigerFraction."*(endnumber-startnumber)+startnumber+1)/2)::int*2";
139                                 $sSQL .= " WHEN interpolationtype='all' THEN (".$this->fTigerFraction."*(endnumber-startnumber)+startnumber)::int";
140                                 $sSQL .= " END as housenumber";
141                                 $sSQL .= " from location_property_tiger where place_id = ".(int)$this->iPlaceID.") as blub1) as blub2";
142                         }
143                         else
144                         {
145                                 $sSQL = "select placex.place_id, partition, osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode, country_code, parent_place_id, linked_place_id, rank_address, rank_search, ";
146                                 $sSQL .= " coalesce(importance,0.75-(rank_search::float/40)) as importance, indexed_status, indexed_date, wikipedia, calculated_country_code, ";
147                                 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
148                                 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
149                                 $sSQL .= " get_name_by_language(name, ARRAY['ref']) as ref,";
150                                 if ($this->bExtraTags) $sSQL .= " hstore_to_json(extratags) as extra,";
151                                 if ($this->bNameDetails) $sSQL .= " hstore_to_json(name) as names,";
152                                 $sSQL .= " (case when centroid is null then st_y(st_centroid(geometry)) else st_y(centroid) end) as lat,";
153                                 $sSQL .= " (case when centroid is null then st_x(st_centroid(geometry)) else st_x(centroid) end) as lon";
154                                 $sSQL .= " from placex where place_id = ".(int)$this->iPlaceID;
155                         }
156
157                         $aPlace = $this->oDB->getRow($sSQL);
158
159
160                         if (PEAR::IsError($aPlace))
161                         {
162                                 failInternalError("Could not lookup place.", $sSQL, $aPlace);
163                         }
164
165                         if (!$aPlace['place_id']) return null;
166
167                         if ($this->bAddressDetails)
168                         {
169                                 if($this->sType == 'tiger') // to get addressdetails for tiger data, the housenumber is needed
170                                         $aAddress = $this->getAddressNames($aPlace['housenumber']);
171                                 else
172                                         $aAddress = $this->getAddressNames();
173                                 $aPlace['aAddress'] = $aAddress;
174                         }
175
176                         if ($this->bExtraTags)
177                         {
178                                 if ($aPlace['extra'])
179                                 {
180                                         $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
181                                 }
182                                 else
183                                 {
184                                         $aPlace['sExtraTags'] = (object) array();
185                                 }
186                         }
187
188                         if ($this->bNameDetails)
189                         {
190                                 if ($aPlace['names'])
191                                 {
192                                         $aPlace['sNameDetails'] = json_decode($aPlace['names']);
193                                 }
194                                 else
195                                 {
196                                         $aPlace['sNameDetails'] = (object) array();
197                                 }
198                         }
199
200                         $aClassType = getClassTypes();
201                         $sAddressType = '';
202                         $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
203                         if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
204                         {
205                                 $sAddressType = $aClassType[$aClassType]['simplelabel'];
206                         }
207                         else
208                         {
209                                 $sClassType = $aPlace['class'].':'.$aPlace['type'];
210                                 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
211                                         $sAddressType = $aClassType[$sClassType]['simplelabel'];
212                                 else $sAddressType = $aPlace['class'];
213                         }
214
215                         $aPlace['addresstype'] = $sAddressType;
216
217                         return $aPlace;
218                 }
219
220                 function getAddressDetails($bAll = false, $housenumber = -1)
221                 {
222                         if (!$this->iPlaceID) return null;
223
224                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
225
226                         $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$this->iPlaceID.",".$housenumber.")";
227                         if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'";
228                         $sSQL .= " order by rank_address desc,isaddress desc";
229
230                         $aAddressLines = $this->oDB->getAll($sSQL);
231                         if (PEAR::IsError($aAddressLines))
232                         {
233                                 var_dump($aAddressLines);
234                                 exit;
235                         }
236                         return $aAddressLines;
237                 }
238
239                 function getAddressNames($housenumber = -1)
240                 {
241                         $aAddressLines = $this->getAddressDetails(false, $housenumber);
242
243                         $aAddress = array();
244                         $aFallback = array();
245                         $aClassType = getClassTypes();
246                         foreach($aAddressLines as $aLine)
247                         {
248                                 $bFallback = false;
249                                 $aTypeLabel = false;
250                                 if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
251                                 elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
252                                 elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
253                                 {
254                                         $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
255                                         $bFallback = true;
256                                 }
257                                 else
258                                 {
259                                         $aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
260                                         $bFallback = true;
261                                 }
262                                 if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
263                                 {
264                                         $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
265                                         $sTypeLabel = str_replace(' ','_',$sTypeLabel);
266                                         if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
267                                         {
268                                                 $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
269                                         }
270                                         $aFallback[$sTypeLabel] = $bFallback;
271                                 }
272                         }
273                         return $aAddress;
274                 }
275
276
277
278                 // returns an array which will contain the keys
279                 //   aBoundingBox
280                 // and may also contain one or more of the keys
281                 //   asgeojson
282                 //   askml
283                 //   assvg
284                 //   astext
285                 //   lat
286                 //   lon
287                 function getOutlines($iPlaceID, $fLon=null, $fLat=null, $fRadius=null)
288                 {
289
290                         $aOutlineResult = array();
291                         if (!$iPlaceID) return $aOutlineResult;
292
293                         if (CONST_Search_AreaPolygons)
294                         {
295                                 // Get the bounding box and outline polygon
296                                 $sSQL  = "select place_id,0 as numfeatures,st_area(geometry) as area,";
297                                 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
298                                 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
299                                 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
300                                 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
301                                 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
302                                 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
303                                 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
304                                 $sFrom = " from placex where place_id = ".$iPlaceID;
305                                 if ($this->fPolygonSimplificationThreshold > 0)
306                                 {
307                                         $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
308                                 }
309                                 else
310                                 {
311                                         $sSQL .= $sFrom;
312                                 }
313
314                                 $aPointPolygon = $this->oDB->getRow($sSQL);
315                                 if (PEAR::IsError($aPointPolygon))
316                                 {
317                                         echo var_dump($aPointPolygon);
318                                         failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
319                                 }
320
321                                 if ($aPointPolygon['place_id'])
322                                 {
323                                         if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
324                                         {
325                                                 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
326                                                 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
327                                         }
328
329                                         if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
330                                         if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
331                                         if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
332                                         if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
333                                         if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
334
335
336                                         if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
337                                         {
338                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
339                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
340                                         }
341                                         if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
342                                         {
343                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
344                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
345                                         }
346
347                                         $aOutlineResult['aBoundingBox'] = array(
348                                                                           (string)$aPointPolygon['minlat'],
349                                                                           (string)$aPointPolygon['maxlat'],
350                                                                           (string)$aPointPolygon['minlon'],
351                                                                           (string)$aPointPolygon['maxlon']
352                                                                          );
353                                 }
354                         } // CONST_Search_AreaPolygons
355
356                         // as a fallback we generate a bounding box without knowing the size of the geometry
357                         if ( (!isset($aOutlineResult['aBoundingBox'])) && isset($fLon) )
358                         {
359
360                                 if ($this->bIncludePolygonAsPoints)
361                                 {
362                                         $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
363                                         $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
364                                 }
365
366                                 $aBounds = array();
367                                 $aBounds['minlat'] = $fLat - $fRadius;
368                                 $aBounds['maxlat'] = $fLat + $fRadius;
369                                 $aBounds['minlon'] = $fLon - $fRadius;
370                                 $aBounds['maxlon'] = $fLon + $fRadius;
371
372                                 $aOutlineResult['aBoundingBox'] = array(
373                                                                   (string)$aBounds['minlat'],
374                                                                   (string)$aBounds['maxlat'],
375                                                                   (string)$aBounds['minlon'],
376                                                                   (string)$aBounds['maxlon']
377                                                                  );
378                         }
379                         return $aOutlineResult;
380                 }
381         }
382 ?>