]> git.openstreetmap.org Git - nominatim.git/blob - lib/ReverseGeocode.php
clean up docs for lookup call
[nominatim.git] / lib / ReverseGeocode.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_BasePath.'/lib/Result.php');
6
7 class ReverseGeocode
8 {
9     protected $oDB;
10     protected $iMaxRank = 28;
11
12
13     public function __construct(&$oDB)
14     {
15         $this->oDB =& $oDB;
16     }
17
18
19     public function setZoom($iZoom)
20     {
21         // Zoom to rank, this could probably be calculated but a lookup gives fine control
22         $aZoomRank = array(
23                       0 => 2, // Continent / Sea
24                       1 => 2,
25                       2 => 2,
26                       3 => 4, // Country
27                       4 => 4,
28                       5 => 8, // State
29                       6 => 10, // Region
30                       7 => 10,
31                       8 => 12, // County
32                       9 => 12,
33                       10 => 17, // City
34                       11 => 17,
35                       12 => 18, // Town / Village
36                       13 => 18,
37                       14 => 22, // Suburb
38                       15 => 22,
39                       16 => 26, // Street, TODO: major street?
40                       17 => 26,
41                       18 => 30, // or >, Building
42                       19 => 30, // or >, Building
43                      );
44         $this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
45     }
46
47     /**
48      * Find the closest interpolation with the given search diameter.
49      *
50      * @param string  $sPointSQL      Reverse geocoding point as SQL
51      * @param float   $fSearchDiam    Search diameter
52      * @param integer $iParentPlaceID Id of parent object
53      *
54      * @return Record of the interpolation or null.
55      */
56     protected function lookupInterpolation($sPointSQL, $fSearchDiam, $iParentPlaceID = null)
57     {
58         $sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search,';
59         $sSQL .= '  ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fraction,';
60         $sSQL .= '  startnumber, endnumber, interpolationtype,';
61         $sSQL .= '  ST_Distance(linegeo,'.$sPointSQL.') as distance';
62         $sSQL .= ' FROM location_property_osmline';
63         $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
64         $sSQL .= ' and indexed_status = 0 and startnumber is not NULL ';
65         if (isset($iParentPlaceID)) {
66             $sSQL .= ' and parent_place_id = '.$iParentPlaceID;
67         }
68         $sSQL .= ' ORDER BY distance ASC limit 1';
69
70         return chksql(
71             $this->oDB->getRow($sSQL),
72             'Could not determine closest housenumber on an osm interpolation line.'
73         );
74     }
75
76     protected function polygonFunctions($sPointSQL, $iMaxRank)
77     {
78         // starts the nopolygonFound function if no polygon is found with the lookupPolygon function
79         $oResult = null;
80
81         $aPlace = $this->lookupPolygon($sPointSQL, $iMaxRank);
82         if ($aPlace) {
83             $oResult = new Result($aPlace['place_id']);
84         // if no polygon which contains the searchpoint is found,
85         // the noPolygonFound function searches in the country_osm_grid table for a polygon
86         } elseif (!$aPlace && $iMaxRank > 4) {
87             $aPlace = $this->noPolygonFound($sPointSQL, $iMaxRank);
88             if ($aPlace) {
89                 $oResult = new Result($aPlace['place_id']);
90             }
91         }
92         return $oResult;
93     }
94
95     protected function noPolygonFound($sPointSQL, $iMaxRank)
96     {
97         // searches for polygon in table country_osm_grid which contains the searchpoint
98         // and searches for the nearest place node to the searchpoint in this polygon
99         $sSQL = 'SELECT country_code FROM country_osm_grid';
100         $sSQL .= ' WHERE ST_CONTAINS (geometry, '.$sPointSQL.') limit 1';
101
102         $aPoly = chksql(
103             $this->oDB->getRow($sSQL),
104             'Could not determine polygon containing the point.'
105         );
106         if ($aPoly) {
107             $sCountryCode = $aPoly['country_code'];
108
109             // look for place nodes with the given country code
110             $sSQL = 'SELECT place_id FROM';
111             $sSQL .= ' (SELECT place_id, rank_search,';
112             $sSQL .= '         ST_distance('.$sPointSQL.', geometry) as distance';
113             $sSQL .= ' FROM placex';
114             $sSQL .= ' WHERE osm_type = \'N\'';
115             $sSQL .= ' AND country_code = \''.$sCountryCode.'\'';
116             $sSQL .= ' AND rank_search between 5 and ' .min(25, $iMaxRank);
117             $sSQL .= ' AND class = \'place\' AND type != \'postcode\'';
118             $sSQL .= ' AND name IS NOT NULL ';
119             $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
120             $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, 5.0)) p ';
121             $sSQL .= 'WHERE distance <= reverse_place_diameter(rank_search)';
122             $sSQL .= ' ORDER BY rank_search DESC, distance ASC';
123             $sSQL .= ' LIMIT 1';
124
125             if (CONST_Debug) var_dump($sSQL);
126             $aPlacNode = chksql(
127                 $this->oDB->getRow($sSQL),
128                 'Could not determine place node.'
129             );
130             if ($aPlacNode) {
131                 return $aPlacNode;
132             }
133
134             // still nothing, then return the country object
135             $sSQL = 'SELECT place_id, ST_distance('.$sPointSQL.', centroid) as distance';
136             $sSQL .= ' FROM placex';
137             $sSQL .= ' WHERE country_code = \''.$sCountryCode.'\'';
138             $sSQL .= ' AND rank_search = 4 AND rank_address = 4';
139             $sSQL .= ' AND class in (\'boundary\',  \'place\')';
140             $sSQL .= ' ORDER BY distance ASC';
141
142             if (CONST_Debug) var_dump($sSQL);
143             $aPlacNode = chksql(
144                 $this->oDB->getRow($sSQL),
145                 'Could not determine place node.'
146             );
147             if ($aPlacNode) {
148                 return $aPlacNode;
149             }
150         }
151     }
152
153     protected function lookupPolygon($sPointSQL, $iMaxRank)
154     {
155         // searches for polygon where the searchpoint is within
156         // if a polygon is found, placenodes with a higher rank are searched inside the polygon
157
158         // polygon search begins at suburb-level
159         if ($iMaxRank > 25) $iMaxRank = 25;
160         // no polygon search over country-level
161         if ($iMaxRank < 5) $iMaxRank = 5;
162         // search for polygon
163         $sSQL = 'SELECT place_id, parent_place_id, rank_address, rank_search FROM';
164         $sSQL .= '(select place_id, parent_place_id, rank_address, rank_search, country_code, geometry';
165         $sSQL .= ' FROM placex';
166         $sSQL .= ' WHERE ST_GeometryType(geometry) in (\'ST_Polygon\', \'ST_MultiPolygon\')';
167         $sSQL .= ' AND rank_address Between 5 AND ' .$iMaxRank;
168         $sSQL .= ' AND geometry && '.$sPointSQL;
169         $sSQL .= ' AND type != \'postcode\' ';
170         $sSQL .= ' AND name is not null';
171         $sSQL .= ' AND indexed_status = 0 and linked_place_id is null';
172         $sSQL .= ' ORDER BY rank_address DESC LIMIT 50 ) as a';
173         $sSQL .= ' WHERE ST_CONTAINS(geometry, '.$sPointSQL.' )';
174         $sSQL .= ' ORDER BY rank_address DESC LIMIT 1';
175
176         $aPoly = chksql(
177             $this->oDB->getRow($sSQL),
178             'Could not determine polygon containing the point.'
179         );
180         if ($aPoly) {
181         // if a polygon is found, search for placenodes begins ...
182             $iParentPlaceID = $aPoly['parent_place_id'];
183             $iRankAddress = $aPoly['rank_address'];
184             $iRankSearch = $aPoly['rank_search'];
185             $iPlaceID = $aPoly['place_id'];
186
187             if ($iRankAddress != $iMaxRank) {
188                 $sSQL = 'SELECT place_id FROM ';
189                 $sSQL .= '(SELECT place_id, rank_search, country_code, geometry,';
190                 $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
191                 $sSQL .= ' FROM placex';
192                 $sSQL .= ' WHERE osm_type = \'N\'';
193                 // using rank_search because of a better differentiation
194                 // for place nodes at rank_address 16
195                 $sSQL .= ' AND rank_search > '.$iRankSearch;
196                 $sSQL .= ' AND rank_search <= '.$iMaxRank;
197                 $sSQL .= ' AND class = \'place\'';
198                 $sSQL .= ' AND type != \'postcode\'';
199                 $sSQL .= ' AND name IS NOT NULL ';
200                 $sSQL .= ' AND indexed_status = 0 AND linked_place_id is null';
201                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, reverse_place_diameter('.$iRankSearch.'::smallint))';
202                 $sSQL .= ' ORDER BY distance ASC,';
203                 $sSQL .= ' rank_address DESC';
204                 $sSQL .= ' limit 500) as a';
205                 $sSQL .= ' WHERE ST_CONTAINS((SELECT geometry FROM placex WHERE place_id = '.$iPlaceID.'), geometry )';
206                 $sSQL .= ' AND distance <= reverse_place_diameter(rank_search)';
207                 $sSQL .= ' ORDER BY distance ASC, rank_search DESC';
208                 $sSQL .= ' LIMIT 1';
209
210                 if (CONST_Debug) var_dump($sSQL);
211                 $aPlacNode = chksql(
212                     $this->oDB->getRow($sSQL),
213                     'Could not determine place node.'
214                 );
215                 if ($aPlacNode) {
216                     return $aPlacNode;
217                 }
218             }
219         }
220         return $aPoly;
221     }
222
223
224     public function lookup($fLat, $fLon, $bDoInterpolation = true)
225     {
226         return $this->lookupPoint(
227             'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)',
228             $bDoInterpolation
229         );
230     }
231
232     public function lookupPoint($sPointSQL, $bDoInterpolation = true)
233     {
234         // starts if the search is on POI or street level,
235         // searches for the nearest POI or street,
236         // if a street is found and a POI is searched for,
237         // the nearest POI which the found street is a parent of is choosen.
238         $iMaxRank = $this->iMaxRank;
239
240         // Find the nearest point
241         $fSearchDiam = 0.006;
242         $oResult = null;
243         $aPlace = null;
244         $fMaxAreaDistance = 1;
245         $bIsTigerStreet = false;
246
247         // for POI or street level
248         if ($iMaxRank >= 26) {
249             $sSQL = 'select place_id,parent_place_id,rank_address,country_code,';
250             $sSQL .= 'CASE WHEN ST_GeometryType(geometry) in (\'ST_Polygon\',\'ST_MultiPolygon\') THEN ST_distance('.$sPointSQL.', centroid)';
251             $sSQL .= ' ELSE ST_distance('.$sPointSQL.', geometry) ';
252             $sSQL .= ' END as distance';
253             $sSQL .= ' FROM ';
254             $sSQL .= ' placex';
255             $sSQL .= '   WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
256             $sSQL .= '   AND';
257             // only streets
258             if ($iMaxRank == 26) {
259                 $sSQL .= ' rank_address = 26';
260             } else {
261                 $sSQL .= ' rank_address between 26 and '.$iMaxRank;
262             }
263             $sSQL .= ' and (name is not null or housenumber is not null';
264             $sSQL .= ' or rank_address between 26 and 27)';
265             $sSQL .= ' and class not in (\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
266             $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
267             $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
268             $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
269             $sSQL .= ' ORDER BY distance ASC limit 1';
270             if (CONST_Debug) var_dump($sSQL);
271             $aPlace = chksql(
272                 $this->oDB->getRow($sSQL),
273                 'Could not determine closest place.'
274             );
275
276             if ($aPlace) {
277                 $iDistance = $aPlace['distance'];
278                 $iPlaceID = $aPlace['place_id'];
279                 $oResult = new Result($iPlaceID);
280                 $iParentPlaceID = $aPlace['parent_place_id'];
281
282                 if ($bDoInterpolation && $iMaxRank >= 30) {
283                     if ($aPlace['rank_address'] <=27) {
284                         $iDistance = 0.001;
285                     }
286                     $aHouse = $this->lookupInterpolation($sPointSQL, $iDistance);
287
288                     if ($aHouse) {
289                         $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
290                         $oResult->iHouseNumber = closestHouseNumber($aHouse);
291                     }
292                 }
293
294                 // if street and maxrank > streetlevel
295                 if (($aPlace['rank_address'] <=27)&& $iMaxRank > 27) {
296                     // find the closest object (up to a certain radius) of which the street is a parent of
297                     $sSQL = ' select place_id,parent_place_id,rank_address,country_code,';
298                     $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
299                     $sSQL .= ' FROM ';
300                     $sSQL .= ' placex';
301                     // radius ?
302                     $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, 0.001)';
303                     $sSQL .= ' AND parent_place_id = '.$iPlaceID;
304                     $sSQL .= ' and rank_address != 28';
305                     $sSQL .= ' and (name is not null or housenumber is not null)';
306                     $sSQL .= ' and class not in (\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
307                     $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
308                     $sSQL .= ' ORDER BY distance ASC limit 1';
309                     if (CONST_Debug) var_dump($sSQL);
310                     $aStreet = chksql(
311                         $this->oDB->getRow($sSQL),
312                         'Could not determine closest place.'
313                     );
314                     if ($aStreet) {
315                         $iDistance = $aStreet['distance'];
316                         $iPlaceID = $aStreet['place_id'];
317                         $oResult = new Result($iPlaceID);
318                         $iParentPlaceID = $aStreet['parent_place_id'];
319
320                         if ($bDoInterpolation && $iMaxRank >= 30) {
321                             $aHouse = $this->lookupInterpolation($sPointSQL, $iDistance, $iParentPlaceID);
322
323                             if ($aHouse) {
324                                 $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
325                                 $oResult->iHouseNumber = closestHouseNumber($aHouse);
326                             }
327                         }
328                     }
329                 }
330
331                   // In the US we can check TIGER data for nearest housenumber
332                 if (CONST_Use_US_Tiger_Data && $aPlace['country_code'] == 'us' && $this->iMaxRank >= 28) {
333                     $fSearchDiam = $aPlace['rank_address'] > 28 ? $aPlace['distance'] : 0.001;
334                     $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search,';
335                     $sSQL .= 'ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fraction,';
336                     $sSQL .= 'ST_distance('.$sPointSQL.', linegeo) as distance,';
337                     $sSQL .= 'startnumber,endnumber,interpolationtype';
338                     $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$oResult->iId;
339                     $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
340                     $sSQL .= ' ORDER BY distance ASC limit 1';
341                     if (CONST_Debug) var_dump($sSQL);
342                     $aPlaceTiger = chksql(
343                         $this->oDB->getRow($sSQL),
344                         'Could not determine closest Tiger place.'
345                     );
346                     if ($aPlaceTiger) {
347                         if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
348                         $aPlace = $aPlaceTiger;
349                         $oResult = new Result($aPlace['place_id'], Result::TABLE_TIGER);
350                         $oResult->iHouseNumber = closestHouseNumber($aPlaceTiger);
351                     }
352                 }
353             // if no POI or street is found ...
354             } else {
355                 $oResult = $this->PolygonFunctions($sPointSQL, $iMaxRank);
356             }
357             // lower than street level ($iMaxRank < 26 )
358         } else {
359             $oResult = $this->PolygonFunctions($sPointSQL, $iMaxRank);
360         }
361         return $oResult;
362     }
363 }