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