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