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