]> git.openstreetmap.org Git - nominatim.git/blob - lib/PlaceLookup.php
Merge remote-tracking branch 'upstream/master'
[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
49     public function setIncludePolygonAsPoints($b = true)
50     {
51         $this->bIncludePolygonAsPoints = $b;
52     }
53
54     public function getIncludePolygonAsPoints()
55     {
56         return $this->bIncludePolygonAsPoints;
57     }
58
59     public function setIncludePolygonAsText($b = true)
60     {
61         $this->bIncludePolygonAsText = $b;
62     }
63
64     public function getIncludePolygonAsText()
65     {
66         return $this->bIncludePolygonAsText;
67     }
68
69     public function setIncludePolygonAsGeoJSON($b = true)
70     {
71         $this->bIncludePolygonAsGeoJSON = $b;
72     }
73
74     public function setIncludePolygonAsKML($b = true)
75     {
76         $this->bIncludePolygonAsKML = $b;
77     }
78
79     public function setIncludePolygonAsSVG($b = true)
80     {
81         $this->bIncludePolygonAsSVG = $b;
82     }
83
84     public function setPolygonSimplificationThreshold($f)
85     {
86         $this->fPolygonSimplificationThreshold = $f;
87     }
88
89     public function lookupOSMID($sType, $iID)
90     {
91         $sSQL = "select place_id from placex where osm_type = '".pg_escape_string($sType)."' and osm_id = ".(int)$iID." order by type = 'postcode' asc";
92         $iPlaceID = chksql($this->oDB->getOne($sSQL));
93
94         return $this->lookup((int)$iPlaceID);
95     }
96
97     public function lookup($iPlaceID, $sType = '', $fInterpolFraction = 0.0)
98     {
99         if (!$iPlaceID) return null;
100
101         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
102         $bIsTiger = CONST_Use_US_Tiger_Data && $sType == 'tiger';
103         $bIsInterpolation = $sType == 'interpolation';
104
105         if ($bIsTiger) {
106             $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,";
107             $sSQL .= " 'us' as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
108             $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, ";
109             $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
110             $sSQL .= " null as placename,";
111             $sSQL .= " null as ref,";
112             if ($this->bExtraTags) $sSQL .= " null as extra,";
113             if ($this->bNameDetails) $sSQL .= " null as names,";
114             $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 ";
115             $sSQL .= " (select *, ";
116             $sSQL .= " GREATEST(startnumber, LEAST(endnumber, CASE WHEN interpolationtype='odd' THEN floor((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
117             $sSQL .= " WHEN interpolationtype='even' THEN ((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
118             $sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
119             $sSQL .= " END)) as housenumber";
120             $sSQL .= " from location_property_tiger where place_id = ".$iPlaceID.") as blub1) as blub2";
121         } elseif ($bIsInterpolation) {
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 .= " GREATEST(startnumber, LEAST(endnumber, 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         } else {
141             $sSQL = "select placex.place_id, partition, osm_type, osm_id, class,";
142             $sSQL .= " type, admin_level, housenumber, street, isin, postcode, country_code,";
143             $sSQL .= " 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             // to get addressdetails for tiger data, the housenumber is needed
161             $iHousenumber = ($bIsTiger || $bIsInterpolation) ? $aPlace['housenumber'] : -1;
162             $aPlace['aAddress'] = $this->getAddressNames($aPlace['place_id'], $iHousenumber);
163         }
164
165         if ($this->bExtraTags) {
166             if ($aPlace['extra']) {
167                 $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
168             } else {
169                 $aPlace['sExtraTags'] = (object) array();
170             }
171         }
172
173         if ($this->bNameDetails) {
174             if ($aPlace['names']) {
175                 $aPlace['sNameDetails'] = json_decode($aPlace['names']);
176             } else {
177                 $aPlace['sNameDetails'] = (object) array();
178             }
179         }
180
181         $aClassType = getClassTypes();
182         $sAddressType = '';
183         $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
184         if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) {
185             $sAddressType = $aClassType[$aClassType]['simplelabel'];
186         } else {
187             $sClassType = $aPlace['class'].':'.$aPlace['type'];
188             if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
189                 $sAddressType = $aClassType[$sClassType]['simplelabel'];
190             else $sAddressType = $aPlace['class'];
191         }
192
193         $aPlace['addresstype'] = $sAddressType;
194
195         return $aPlace;
196     }
197
198     public function getAddressDetails($iPlaceID, $bAll = false, $housenumber = -1)
199     {
200         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
201
202         $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$iPlaceID.",".$housenumber.")";
203         if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'";
204         $sSQL .= " order by rank_address desc,isaddress desc";
205
206         return chksql($this->oDB->getAll($sSQL));
207     }
208
209     public function getAddressNames($iPlaceID, $housenumber = -1)
210     {
211         $aAddressLines = $this->getAddressDetails($iPlaceID, false, $housenumber);
212
213         $aAddress = array();
214         $aFallback = array();
215         $aClassType = getClassTypes();
216         foreach ($aAddressLines as $aLine) {
217             $bFallback = false;
218             $aTypeLabel = false;
219             if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
220                 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
221             } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
222                 $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
223             } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
224                 $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
225                 $bFallback = true;
226             } else {
227                 $aTypeLabel = array('simplelabel' => 'address'.$aLine['rank_address']);
228                 $bFallback = true;
229             }
230             if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
231                 $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
232                 $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
233                 if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
234                     $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
235                 }
236                 $aFallback[$sTypeLabel] = $bFallback;
237             }
238         }
239         return $aAddress;
240     }
241
242
243
244     /* returns an array which will contain the keys
245      *   aBoundingBox
246      * and may also contain one or more of the keys
247      *   asgeojson
248      *   askml
249      *   assvg
250      *   astext
251      *   lat
252      *   lon
253      */
254
255
256     public function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null)
257     {
258
259         $aOutlineResult = array();
260         if (!$iPlaceID) return $aOutlineResult;
261
262         if (CONST_Search_AreaPolygons) {
263             // Get the bounding box and outline polygon
264             $sSQL  = "select place_id,0 as numfeatures,st_area(geometry) as area,";
265             $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
266             $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
267             $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
268             if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
269             if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
270             if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
271             if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
272             $sFrom = " from placex where place_id = ".$iPlaceID;
273             if ($this->fPolygonSimplificationThreshold > 0) {
274                 $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
275             } else {
276                 $sSQL .= $sFrom;
277             }
278
279             $aPointPolygon = chksql($this->oDB->getRow($sSQL), "Could not get outline");
280
281             if ($aPointPolygon['place_id']) {
282                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
283                     $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
284                     $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
285                 }
286
287                 if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
288                 if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
289                 if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
290                 if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
291                 if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
292
293
294                 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
295                     $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
296                     $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
297                 }
298
299                 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
300                     $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
301                     $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
302                 }
303
304                 $aOutlineResult['aBoundingBox'] = array(
305                                                    (string)$aPointPolygon['minlat'],
306                                                    (string)$aPointPolygon['maxlat'],
307                                                    (string)$aPointPolygon['minlon'],
308                                                    (string)$aPointPolygon['maxlon']
309                                                   );
310             }
311         }
312
313         // as a fallback we generate a bounding box without knowing the size of the geometry
314         if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
315             //
316             if ($this->bIncludePolygonAsPoints) {
317                 $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
318                 $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
319             }
320
321             $aBounds = array();
322             $aBounds['minlat'] = $fLat - $fRadius;
323             $aBounds['maxlat'] = $fLat + $fRadius;
324             $aBounds['minlon'] = $fLon - $fRadius;
325             $aBounds['maxlon'] = $fLon + $fRadius;
326
327             $aOutlineResult['aBoundingBox'] = array(
328                                                (string)$aBounds['minlat'],
329                                                (string)$aBounds['maxlat'],
330                                                (string)$aBounds['minlon'],
331                                                (string)$aBounds['maxlon']
332                                               );
333         }
334         return $aOutlineResult;
335     }
336 }