]> git.openstreetmap.org Git - nominatim.git/blob - lib/PlaceLookup.php
Merge remote-tracking branch 'markus/master' into master
[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->fInterpolFraction = $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 (CONST_Use_US_Tiger_Data && $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->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
138                                 $sSQL .= " WHEN interpolationtype='even' THEN ((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
139                                 $sSQL .= " WHEN interpolationtype='all' THEN (".$this->fInterpolFraction."*(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 if ($this->sType == 'interpolation')
144                         {
145                                 $sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,";
146                                 $sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
147                                 $sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, ";
148                                 $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
149                                 $sSQL .= " null as placename,";
150                                 $sSQL .= " null as ref,";
151                                 if ($this->bExtraTags) $sSQL .= " null as extra,";
152                                 if ($this->bNameDetails) $sSQL .= " null as names,";
153                                 $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 ";
154                                 $sSQL .= " (select *, ";
155                                 $sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
156                                 $sSQL .= " WHEN interpolationtype='even' THEN ((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
157                                 $sSQL .= " WHEN interpolationtype='all' THEN (".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
158                                 $sSQL .= " END as housenumber";
159                                 $sSQL .= " from location_property_osmline where place_id = ".(int)$this->iPlaceID.") as blub1) as blub2";
160                                 // testcase: interpolationtype=odd, startnumber=1000, endnumber=1006, fInterpolFraction=1 => housenumber=1007 => error in st_lineinterpolatepoint
161                                 // 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)
162                                 // and not interpolated
163                         }
164                         else
165                         {
166                                 $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, ";
167                                 $sSQL .= " coalesce(importance,0.75-(rank_search::float/40)) as importance, indexed_status, indexed_date, wikipedia, calculated_country_code, ";
168                                 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
169                                 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
170                                 $sSQL .= " get_name_by_language(name, ARRAY['ref']) as ref,";
171                                 if ($this->bExtraTags) $sSQL .= " hstore_to_json(extratags) as extra,";
172                                 if ($this->bNameDetails) $sSQL .= " hstore_to_json(name) as names,";
173                                 $sSQL .= " (case when centroid is null then st_y(st_centroid(geometry)) else st_y(centroid) end) as lat,";
174                                 $sSQL .= " (case when centroid is null then st_x(st_centroid(geometry)) else st_x(centroid) end) as lon";
175                                 $sSQL .= " from placex where place_id = ".(int)$this->iPlaceID;
176                         }
177
178                         $aPlace = $this->oDB->getRow($sSQL);
179
180
181                         if (PEAR::IsError($aPlace))
182                         {
183                                 failInternalError("Could not lookup place.", $sSQL, $aPlace);
184                         }
185
186                         if (!$aPlace['place_id']) return null;
187
188                         if ($this->bAddressDetails)
189                         {
190                                 if(CONST_Use_US_Tiger_Data && $this->sType == 'tiger' || $this->sType == 'interpolation') // to get addressdetails for tiger data, the housenumber is needed
191                                         $aAddress = $this->getAddressNames($aPlace['housenumber']);
192                                 else
193                                         $aAddress = $this->getAddressNames();
194                                 $aPlace['aAddress'] = $aAddress;
195                         }
196
197                         if ($this->bExtraTags)
198                         {
199                                 if ($aPlace['extra'])
200                                 {
201                                         $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
202                                 }
203                                 else
204                                 {
205                                         $aPlace['sExtraTags'] = (object) array();
206                                 }
207                         }
208
209                         if ($this->bNameDetails)
210                         {
211                                 if ($aPlace['names'])
212                                 {
213                                         $aPlace['sNameDetails'] = json_decode($aPlace['names']);
214                                 }
215                                 else
216                                 {
217                                         $aPlace['sNameDetails'] = (object) array();
218                                 }
219                         }
220
221                         $aClassType = getClassTypes();
222                         $sAddressType = '';
223                         $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
224                         if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
225                         {
226                                 $sAddressType = $aClassType[$aClassType]['simplelabel'];
227                         }
228                         else
229                         {
230                                 $sClassType = $aPlace['class'].':'.$aPlace['type'];
231                                 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
232                                         $sAddressType = $aClassType[$sClassType]['simplelabel'];
233                                 else $sAddressType = $aPlace['class'];
234                         }
235
236                         $aPlace['addresstype'] = $sAddressType;
237
238                         return $aPlace;
239                 }
240
241                 function getAddressDetails($bAll = false, $housenumber = -1)
242                 {
243                         if (!$this->iPlaceID) return null;
244
245                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
246
247                         $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$this->iPlaceID.",".$housenumber.")";
248                         if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'";
249                         $sSQL .= " order by rank_address desc,isaddress desc";
250
251                         $aAddressLines = $this->oDB->getAll($sSQL);
252                         if (PEAR::IsError($aAddressLines))
253                         {
254                                 var_dump($aAddressLines);
255                                 exit;
256                         }
257                         return $aAddressLines;
258                 }
259
260                 function getAddressNames($housenumber = -1)
261                 {
262                         $aAddressLines = $this->getAddressDetails(false, $housenumber);
263
264                         $aAddress = array();
265                         $aFallback = array();
266                         $aClassType = getClassTypes();
267                         foreach($aAddressLines as $aLine)
268                         {
269                                 $bFallback = false;
270                                 $aTypeLabel = false;
271                                 if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
272                                 elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
273                                 elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
274                                 {
275                                         $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
276                                         $bFallback = true;
277                                 }
278                                 else
279                                 {
280                                         $aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
281                                         $bFallback = true;
282                                 }
283                                 if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
284                                 {
285                                         $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
286                                         $sTypeLabel = str_replace(' ','_',$sTypeLabel);
287                                         if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
288                                         {
289                                                 $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
290                                         }
291                                         $aFallback[$sTypeLabel] = $bFallback;
292                                 }
293                         }
294                         return $aAddress;
295                 }
296
297
298
299                 // returns an array which will contain the keys
300                 //   aBoundingBox
301                 // and may also contain one or more of the keys
302                 //   asgeojson
303                 //   askml
304                 //   assvg
305                 //   astext
306                 //   lat
307                 //   lon
308                 function getOutlines($iPlaceID, $fLon=null, $fLat=null, $fRadius=null)
309                 {
310
311                         $aOutlineResult = array();
312                         if (!$iPlaceID) return $aOutlineResult;
313
314                         if (CONST_Search_AreaPolygons)
315                         {
316                                 // Get the bounding box and outline polygon
317                                 $sSQL  = "select place_id,0 as numfeatures,st_area(geometry) as area,";
318                                 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
319                                 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
320                                 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
321                                 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
322                                 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
323                                 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
324                                 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
325                                 $sFrom = " from placex where place_id = ".$iPlaceID;
326                                 if ($this->fPolygonSimplificationThreshold > 0)
327                                 {
328                                         $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
329                                 }
330                                 else
331                                 {
332                                         $sSQL .= $sFrom;
333                                 }
334
335                                 $aPointPolygon = $this->oDB->getRow($sSQL);
336                                 if (PEAR::IsError($aPointPolygon))
337                                 {
338                                         echo var_dump($aPointPolygon);
339                                         failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
340                                 }
341
342                                 if ($aPointPolygon['place_id'])
343                                 {
344                                         if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
345                                         {
346                                                 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
347                                                 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
348                                         }
349
350                                         if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
351                                         if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
352                                         if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
353                                         if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
354                                         if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
355
356
357                                         if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
358                                         {
359                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
360                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
361                                         }
362                                         if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
363                                         {
364                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
365                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
366                                         }
367
368                                         $aOutlineResult['aBoundingBox'] = array(
369                                                                           (string)$aPointPolygon['minlat'],
370                                                                           (string)$aPointPolygon['maxlat'],
371                                                                           (string)$aPointPolygon['minlon'],
372                                                                           (string)$aPointPolygon['maxlon']
373                                                                          );
374                                 }
375                         } // CONST_Search_AreaPolygons
376
377                         // as a fallback we generate a bounding box without knowing the size of the geometry
378                         if ( (!isset($aOutlineResult['aBoundingBox'])) && isset($fLon) )
379                         {
380
381                                 if ($this->bIncludePolygonAsPoints)
382                                 {
383                                         $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
384                                         $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
385                                 }
386
387                                 $aBounds = array();
388                                 $aBounds['minlat'] = $fLat - $fRadius;
389                                 $aBounds['maxlat'] = $fLat + $fRadius;
390                                 $aBounds['minlon'] = $fLon - $fRadius;
391                                 $aBounds['maxlon'] = $fLon + $fRadius;
392
393                                 $aOutlineResult['aBoundingBox'] = array(
394                                                                   (string)$aBounds['minlat'],
395                                                                   (string)$aBounds['maxlat'],
396                                                                   (string)$aBounds['minlon'],
397                                                                   (string)$aBounds['maxlon']
398                                                                  );
399                         }
400                         return $aOutlineResult;
401                 }
402         }
403 ?>