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