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