]> git.openstreetmap.org Git - nominatim.git/blob - lib/ReverseGeocode.php
directly do country search for reverse zoom < 5
[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         if ($iMaxRank > 4) {
82             $aPlace = $this->lookupPolygon($sPointSQL, $iMaxRank);
83             if ($aPlace) {
84                 $oResult = new Result($aPlace['place_id']);
85             }
86         }
87         // if no polygon which contains the searchpoint is found,
88         // the noPolygonFound function searches in the country_osm_grid table for a polygon
89         if (!$oResult) {
90             $aPlace = $this->noPolygonFound($sPointSQL, $iMaxRank);
91             if ($aPlace) {
92                 $oResult = new Result($aPlace['place_id']);
93             }
94         }
95         return $oResult;
96     }
97
98     protected function noPolygonFound($sPointSQL, $iMaxRank)
99     {
100         // searches for polygon in table country_osm_grid which contains the searchpoint
101         // and searches for the nearest place node to the searchpoint in this polygon
102         $sSQL = 'SELECT country_code FROM country_osm_grid';
103         $sSQL .= ' WHERE ST_CONTAINS (geometry, '.$sPointSQL.') limit 1';
104
105         $aPoly = chksql(
106             $this->oDB->getRow($sSQL),
107             'Could not determine country polygon containing the point.'
108         );
109         if ($aPoly) {
110             $sCountryCode = $aPoly['country_code'];
111
112             if ($iMaxRank > 4) {
113                 // look for place nodes with the given country code
114                 $sSQL = 'SELECT place_id FROM';
115                 $sSQL .= ' (SELECT place_id, rank_search,';
116                 $sSQL .= '         ST_distance('.$sPointSQL.', geometry) as distance';
117                 $sSQL .= ' FROM placex';
118                 $sSQL .= ' WHERE osm_type = \'N\'';
119                 $sSQL .= ' AND country_code = \''.$sCountryCode.'\'';
120                 $sSQL .= ' AND rank_search between 5 and ' .min(25, $iMaxRank);
121                 $sSQL .= ' AND class = \'place\' AND type != \'postcode\'';
122                 $sSQL .= ' AND name IS NOT NULL ';
123                 $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
124                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, 1.8)) p ';
125                 $sSQL .= 'WHERE distance <= reverse_place_diameter(rank_search)';
126                 $sSQL .= ' ORDER BY rank_search DESC, distance ASC';
127                 $sSQL .= ' LIMIT 1';
128
129                 if (CONST_Debug) var_dump($sSQL);
130                 $aPlacNode = chksql(
131                     $this->oDB->getRow($sSQL),
132                     'Could not determine place node.'
133                 );
134                 if ($aPlacNode) {
135                     return $aPlacNode;
136                 }
137             }
138
139             // still nothing, then return the country object
140             $sSQL = 'SELECT place_id, ST_distance('.$sPointSQL.', centroid) as distance';
141             $sSQL .= ' FROM placex';
142             $sSQL .= ' WHERE country_code = \''.$sCountryCode.'\'';
143             $sSQL .= ' AND rank_search = 4 AND rank_address = 4';
144             $sSQL .= ' AND class in (\'boundary\',  \'place\')';
145             $sSQL .= ' ORDER BY distance ASC';
146
147             if (CONST_Debug) var_dump($sSQL);
148             $aPlacNode = chksql(
149                 $this->oDB->getRow($sSQL),
150                 'Could not determine place node.'
151             );
152             if ($aPlacNode) {
153                 return $aPlacNode;
154             }
155         }
156     }
157
158     protected function lookupPolygon($sPointSQL, $iMaxRank)
159     {
160         // searches for polygon where the searchpoint is within
161         // if a polygon is found, placenodes with a higher rank are searched inside the polygon
162
163         // polygon search begins at suburb-level
164         if ($iMaxRank > 25) $iMaxRank = 25;
165         // no polygon search over country-level
166         if ($iMaxRank < 5) $iMaxRank = 5;
167         // search for polygon
168         $sSQL = 'SELECT place_id, parent_place_id, rank_address, rank_search FROM';
169         $sSQL .= '(select place_id, parent_place_id, rank_address, rank_search, country_code, geometry';
170         $sSQL .= ' FROM placex';
171         $sSQL .= ' WHERE ST_GeometryType(geometry) in (\'ST_Polygon\', \'ST_MultiPolygon\')';
172         $sSQL .= ' AND rank_address Between 5 AND ' .$iMaxRank;
173         $sSQL .= ' AND geometry && '.$sPointSQL;
174         $sSQL .= ' AND type != \'postcode\' ';
175         $sSQL .= ' AND name is not null';
176         $sSQL .= ' AND indexed_status = 0 and linked_place_id is null';
177         $sSQL .= ' ORDER BY rank_address DESC LIMIT 50 ) as a';
178         $sSQL .= ' WHERE ST_CONTAINS(geometry, '.$sPointSQL.' )';
179         $sSQL .= ' ORDER BY rank_address DESC LIMIT 1';
180
181         $aPoly = chksql(
182             $this->oDB->getRow($sSQL),
183             'Could not determine polygon containing the point.'
184         );
185         if ($aPoly) {
186         // if a polygon is found, search for placenodes begins ...
187             $iParentPlaceID = $aPoly['parent_place_id'];
188             $iRankAddress = $aPoly['rank_address'];
189             $iRankSearch = $aPoly['rank_search'];
190             $iPlaceID = $aPoly['place_id'];
191
192             if ($iRankAddress != $iMaxRank) {
193                 $sSQL = 'SELECT place_id FROM ';
194                 $sSQL .= '(SELECT place_id, rank_search, country_code, geometry,';
195                 $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
196                 $sSQL .= ' FROM placex';
197                 $sSQL .= ' WHERE osm_type = \'N\'';
198                 // using rank_search because of a better differentiation
199                 // for place nodes at rank_address 16
200                 $sSQL .= ' AND rank_search > '.$iRankSearch;
201                 $sSQL .= ' AND rank_search <= '.$iMaxRank;
202                 $sSQL .= ' AND class = \'place\'';
203                 $sSQL .= ' AND type != \'postcode\'';
204                 $sSQL .= ' AND name IS NOT NULL ';
205                 $sSQL .= ' AND indexed_status = 0 AND linked_place_id is null';
206                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, reverse_place_diameter('.$iRankSearch.'::smallint))';
207                 $sSQL .= ' ORDER BY distance ASC,';
208                 $sSQL .= ' rank_address DESC';
209                 $sSQL .= ' limit 500) as a';
210                 $sSQL .= ' WHERE ST_CONTAINS((SELECT geometry FROM placex WHERE place_id = '.$iPlaceID.'), geometry )';
211                 $sSQL .= ' AND distance <= reverse_place_diameter(rank_search)';
212                 $sSQL .= ' ORDER BY distance ASC, rank_search DESC';
213                 $sSQL .= ' LIMIT 1';
214
215                 if (CONST_Debug) var_dump($sSQL);
216                 $aPlacNode = chksql(
217                     $this->oDB->getRow($sSQL),
218                     'Could not determine place node.'
219                 );
220                 if ($aPlacNode) {
221                     return $aPlacNode;
222                 }
223             }
224         }
225         return $aPoly;
226     }
227
228
229     public function lookup($fLat, $fLon, $bDoInterpolation = true)
230     {
231         return $this->lookupPoint(
232             'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)',
233             $bDoInterpolation
234         );
235     }
236
237     public function lookupPoint($sPointSQL, $bDoInterpolation = true)
238     {
239         // starts if the search is on POI or street level,
240         // searches for the nearest POI or street,
241         // if a street is found and a POI is searched for,
242         // the nearest POI which the found street is a parent of is choosen.
243         $iMaxRank = $this->iMaxRank;
244
245         // Find the nearest point
246         $fSearchDiam = 0.006;
247         $oResult = null;
248         $aPlace = null;
249         $fMaxAreaDistance = 1;
250         $bIsTigerStreet = false;
251
252         // for POI or street level
253         if ($iMaxRank >= 26) {
254             $sSQL = 'select place_id,parent_place_id,rank_address,country_code,';
255             $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
256             $sSQL .= ' FROM ';
257             $sSQL .= ' placex';
258             $sSQL .= '   WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
259             $sSQL .= '   AND';
260             // only streets
261             if ($iMaxRank == 26) {
262                 $sSQL .= ' rank_address = 26';
263             } else {
264                 $sSQL .= ' rank_address between 26 and '.$iMaxRank;
265             }
266             $sSQL .= ' and (name is not null or housenumber is not null';
267             $sSQL .= ' or rank_address between 26 and 27)';
268             $sSQL .= ' and class not in (\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
269             $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
270             $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
271             $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
272             $sSQL .= ' ORDER BY distance ASC limit 1';
273             if (CONST_Debug) var_dump($sSQL);
274             $aPlace = chksql(
275                 $this->oDB->getRow($sSQL),
276                 'Could not determine closest place.'
277             );
278
279             if ($aPlace) {
280                 $iDistance = $aPlace['distance'];
281                 $iPlaceID = $aPlace['place_id'];
282                 $oResult = new Result($iPlaceID);
283                 $iParentPlaceID = $aPlace['parent_place_id'];
284
285                 if ($bDoInterpolation && $iMaxRank >= 30) {
286                     if ($aPlace['rank_address'] <=27) {
287                         $iDistance = 0.001;
288                     }
289                     $aHouse = $this->lookupInterpolation($sPointSQL, $iDistance);
290
291                     if ($aHouse) {
292                         $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
293                         $oResult->iHouseNumber = closestHouseNumber($aHouse);
294                     }
295                 }
296
297                 // if street and maxrank > streetlevel
298                 if (($aPlace['rank_address'] <=27)&& $iMaxRank > 27) {
299                     // find the closest object (up to a certain radius) of which the street is a parent of
300                     $sSQL = ' select place_id,parent_place_id,rank_address,country_code,';
301                     $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
302                     $sSQL .= ' FROM ';
303                     $sSQL .= ' placex';
304                     // radius ?
305                     $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, 0.001)';
306                     $sSQL .= ' AND parent_place_id = '.$iPlaceID;
307                     $sSQL .= ' and rank_address != 28';
308                     $sSQL .= ' and (name is not null or housenumber is not null)';
309                     $sSQL .= ' and class not in (\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
310                     $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
311                     $sSQL .= ' ORDER BY distance ASC limit 1';
312                     if (CONST_Debug) var_dump($sSQL);
313                     $aStreet = chksql(
314                         $this->oDB->getRow($sSQL),
315                         'Could not determine closest place.'
316                     );
317                     if ($aStreet) {
318                         $iDistance = $aStreet['distance'];
319                         $iPlaceID = $aStreet['place_id'];
320                         $oResult = new Result($iPlaceID);
321                         $iParentPlaceID = $aStreet['parent_place_id'];
322
323                         if ($bDoInterpolation && $iMaxRank >= 30) {
324                             $aHouse = $this->lookupInterpolation($sPointSQL, $iDistance, $iParentPlaceID);
325
326                             if ($aHouse) {
327                                 $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
328                                 $oResult->iHouseNumber = closestHouseNumber($aHouse);
329                             }
330                         }
331                     }
332                 }
333
334                   // In the US we can check TIGER data for nearest housenumber
335                 if (CONST_Use_US_Tiger_Data && $aPlace['country_code'] == 'us' && $this->iMaxRank >= 28) {
336                     $fSearchDiam = $aPlace['rank_address'] > 28 ? $aPlace['distance'] : 0.001;
337                     $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search,';
338                     $sSQL .= 'ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fraction,';
339                     $sSQL .= 'ST_distance('.$sPointSQL.', linegeo) as distance,';
340                     $sSQL .= 'startnumber,endnumber,interpolationtype';
341                     $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$oResult->iId;
342                     $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
343                     $sSQL .= ' ORDER BY distance ASC limit 1';
344                     if (CONST_Debug) var_dump($sSQL);
345                     $aPlaceTiger = chksql(
346                         $this->oDB->getRow($sSQL),
347                         'Could not determine closest Tiger place.'
348                     );
349                     if ($aPlaceTiger) {
350                         if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
351                         $aPlace = $aPlaceTiger;
352                         $oResult = new Result($aPlace['place_id'], Result::TABLE_TIGER);
353                         $oResult->iHouseNumber = closestHouseNumber($aPlaceTiger);
354                     }
355                 }
356             // if no POI or street is found ...
357             } else {
358                 $oResult = $this->PolygonFunctions($sPointSQL, $iMaxRank);
359             }
360             // lower than street level ($iMaxRank < 26 )
361         } else {
362             $oResult = $this->PolygonFunctions($sPointSQL, $iMaxRank);
363         }
364         return $oResult;
365     }
366 }