]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/ReverseGeocode.php
don't even try heavily penalized searches
[nominatim.git] / lib-php / ReverseGeocode.php
1 <?php
2 /**
3  * SPDX-License-Identifier: GPL-2.0-only
4  *
5  * This file is part of Nominatim. (https://nominatim.org)
6  *
7  * Copyright (C) 2022 by the Nominatim developer community.
8  * For a full list of authors see the git log.
9  */
10
11 namespace Nominatim;
12
13 require_once(CONST_LibDir.'/Result.php');
14
15 class ReverseGeocode
16 {
17     protected $oDB;
18     protected $iMaxRank = 28;
19
20
21     public function __construct(&$oDB)
22     {
23         $this->oDB =& $oDB;
24     }
25
26
27     public function setZoom($iZoom)
28     {
29         // Zoom to rank, this could probably be calculated but a lookup gives fine control
30         $aZoomRank = array(
31                       0 => 2, // Continent / Sea
32                       1 => 2,
33                       2 => 2,
34                       3 => 4, // Country
35                       4 => 4,
36                       5 => 8, // State
37                       6 => 10, // Region
38                       7 => 10,
39                       8 => 12, // County
40                       9 => 12,
41                       10 => 17, // City
42                       11 => 17,
43                       12 => 18, // Town
44                       13 => 19, // Village
45                       14 => 22, // Neighbourhood
46                       15 => 25, // Locality
47                       16 => 26, // major street
48                       17 => 27, // minor street
49                       18 => 30, // or >, Building
50                       19 => 30, // or >, Building
51                      );
52         $this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
53     }
54
55     /**
56      * Find the closest interpolation with the given search diameter.
57      *
58      * @param string $sPointSQL   Reverse geocoding point as SQL
59      * @param float  $fSearchDiam Search diameter
60      *
61      * @return Record of the interpolation or null.
62      */
63     protected function lookupInterpolation($sPointSQL, $fSearchDiam)
64     {
65         Debug::newFunction('lookupInterpolation');
66         $sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search,';
67         $sSQL .= '  (CASE WHEN endnumber != startnumber';
68         $sSQL .= '        THEN (endnumber - startnumber) * ST_LineLocatePoint(linegeo,'.$sPointSQL.')';
69         $sSQL .= '        ELSE startnumber END) as fhnr,';
70         $sSQL .= '  startnumber, endnumber, step,';
71         $sSQL .= '  ST_Distance(linegeo,'.$sPointSQL.') as distance';
72         $sSQL .= ' FROM location_property_osmline';
73         $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
74         $sSQL .= '       and indexed_status = 0 and startnumber is not NULL ';
75         $sSQL .= '       and parent_place_id != 0';
76         $sSQL .= ' ORDER BY distance ASC limit 1';
77         Debug::printSQL($sSQL);
78
79         return $this->oDB->getRow(
80             $sSQL,
81             null,
82             'Could not determine closest housenumber on an osm interpolation line.'
83         );
84     }
85
86     protected function lookupLargeArea($sPointSQL, $iMaxRank)
87     {
88         $sCountryCode = $this->getCountryCode($sPointSQL);
89         if (CONST_Search_WithinCountries and $sCountryCode == null) {
90             return  null;
91         }
92
93         if ($iMaxRank > 4) {
94             $aPlace = $this->lookupPolygon($sPointSQL, $iMaxRank);
95             if ($aPlace) {
96                 return new Result($aPlace['place_id']);
97             }
98         }
99
100         // If no polygon which contains the searchpoint is found,
101         // searches in the country_osm_grid table for a polygon.
102         return  $this->lookupInCountry($sPointSQL, $iMaxRank, $sCountryCode);
103     }
104
105     protected function getCountryCode($sPointSQL)
106     {
107         Debug::newFunction('getCountryCode');
108         // searches for polygon in table country_osm_grid which contains the searchpoint
109         // and searches for the nearest place node to the searchpoint in this polygon
110         $sSQL = 'SELECT country_code FROM country_osm_grid';
111         $sSQL .= ' WHERE ST_CONTAINS(geometry, '.$sPointSQL.') LIMIT 1';
112         Debug::printSQL($sSQL);
113
114         $sCountryCode = $this->oDB->getOne(
115             $sSQL,
116             null,
117             'Could not determine country polygon containing the point.'
118         );
119         return $sCountryCode;
120     }
121
122     protected function lookupInCountry($sPointSQL, $iMaxRank, $sCountryCode)
123     {
124         Debug::newFunction('lookupInCountry');
125         if ($sCountryCode) {
126             if ($iMaxRank > 4) {
127                 // look for place nodes with the given country code
128                 $sSQL = 'SELECT place_id FROM';
129                 $sSQL .= ' (SELECT place_id, rank_search,';
130                 $sSQL .= '         ST_distance('.$sPointSQL.', geometry) as distance';
131                 $sSQL .= ' FROM placex';
132                 $sSQL .= ' WHERE osm_type = \'N\'';
133                 $sSQL .= ' AND country_code = \''.$sCountryCode.'\'';
134                 $sSQL .= ' AND rank_address between 4 and 25'; // needed to select right index
135                 $sSQL .= ' AND rank_search between 5 and ' .min(25, $iMaxRank);
136                 $sSQL .= ' AND type != \'postcode\'';
137                 $sSQL .= ' AND name IS NOT NULL ';
138                 $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
139                 $sSQL .= ' AND ST_Buffer(geometry, reverse_place_diameter(rank_search)) && '.$sPointSQL;
140                 $sSQL .= ') as a ';
141                 $sSQL .= 'WHERE distance <= reverse_place_diameter(rank_search)';
142                 $sSQL .= ' ORDER BY rank_search DESC, distance ASC';
143                 $sSQL .= ' LIMIT 1';
144                 Debug::printSQL($sSQL);
145
146                 $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
147                 Debug::printVar('Country node', $aPlace);
148
149                 if ($aPlace) {
150                     return new Result($aPlace['place_id']);
151                 }
152             }
153
154             // still nothing, then return the country object
155             $sSQL = 'SELECT place_id, ST_distance('.$sPointSQL.', centroid) as distance';
156             $sSQL .= ' FROM placex';
157             $sSQL .= ' WHERE country_code = \''.$sCountryCode.'\'';
158             $sSQL .= ' AND rank_search = 4 AND rank_address = 4';
159             $sSQL .= ' AND class in (\'boundary\',  \'place\')';
160             $sSQL .= ' AND linked_place_id is null';
161             $sSQL .= ' ORDER BY distance ASC';
162             Debug::printSQL($sSQL);
163
164             $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
165             Debug::printVar('Country place', $aPlace);
166             if ($aPlace) {
167                 return new Result($aPlace['place_id']);
168             }
169         }
170
171         return null;
172     }
173
174     /**
175      * Search for areas or nodes for areas or nodes between state and suburb level.
176      *
177      * @param string $sPointSQL Search point as SQL string.
178      * @param int    $iMaxRank  Maximum address rank of the feature.
179      *
180      * @return Record of the found feature or null.
181      *
182      * Searches first for polygon that contains the search point.
183      * If such a polygon is found, place nodes with a higher rank are
184      * searched inside the polygon.
185      */
186     protected function lookupPolygon($sPointSQL, $iMaxRank)
187     {
188         Debug::newFunction('lookupPolygon');
189         // polygon search begins at suburb-level
190         if ($iMaxRank > 25) {
191             $iMaxRank = 25;
192         }
193         // no polygon search over country-level
194         if ($iMaxRank < 5) {
195             $iMaxRank = 5;
196         }
197         // search for polygon
198         $sSQL = 'SELECT place_id, parent_place_id, rank_address, rank_search FROM';
199         $sSQL .= '(select place_id, parent_place_id, rank_address, rank_search, country_code, geometry';
200         $sSQL .= ' FROM placex';
201         $sSQL .= ' WHERE ST_GeometryType(geometry) in (\'ST_Polygon\', \'ST_MultiPolygon\')';
202         // Ensure that query planner doesn't use the index on rank_search.
203         $sSQL .= ' AND coalesce(rank_search, 0) between 5 and ' .$iMaxRank;
204         $sSQL .= ' AND rank_address between 4 and 25'; // needed for index selection
205         $sSQL .= ' AND geometry && '.$sPointSQL;
206         $sSQL .= ' AND type != \'postcode\' ';
207         $sSQL .= ' AND name is not null';
208         $sSQL .= ' AND indexed_status = 0 and linked_place_id is null';
209         $sSQL .= ' ORDER BY rank_search DESC LIMIT 50 ) as a';
210         $sSQL .= ' WHERE ST_Contains(geometry, '.$sPointSQL.' )';
211         $sSQL .= ' ORDER BY rank_search DESC LIMIT 1';
212         Debug::printSQL($sSQL);
213
214         $aPoly = $this->oDB->getRow($sSQL, null, 'Could not determine polygon containing the point.');
215         Debug::printVar('Polygon result', $aPoly);
216
217         if ($aPoly) {
218         // if a polygon is found, search for placenodes begins ...
219             $iRankAddress = $aPoly['rank_address'];
220             $iRankSearch = $aPoly['rank_search'];
221             $iPlaceID = $aPoly['place_id'];
222
223             if ($iRankSearch != $iMaxRank) {
224                 $sSQL = 'SELECT place_id FROM ';
225                 $sSQL .= '(SELECT place_id, rank_search, country_code, geometry,';
226                 $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
227                 $sSQL .= ' FROM placex';
228                 $sSQL .= ' WHERE osm_type = \'N\'';
229                 $sSQL .= ' AND rank_search > '.$iRankSearch;
230                 $sSQL .= ' AND rank_search <= '.$iMaxRank;
231                 $sSQL .= ' AND rank_address between 4 and 25';  // needed to select right index
232                 $sSQL .= ' AND type != \'postcode\'';
233                 $sSQL .= ' AND name IS NOT NULL ';
234                 $sSQL .= ' AND indexed_status = 0 AND linked_place_id is null';
235                 $sSQL .= ' AND ST_Buffer(geometry, reverse_place_diameter(rank_search)) && '.$sPointSQL;
236                 $sSQL .= ' ORDER BY rank_search DESC, distance ASC';
237                 $sSQL .= ' limit 100) as a';
238                 $sSQL .= ' WHERE ST_Contains((SELECT geometry FROM placex WHERE place_id = '.$iPlaceID.'), geometry )';
239                 $sSQL .= ' AND distance <= reverse_place_diameter(rank_search)';
240                 $sSQL .= ' ORDER BY rank_search DESC, distance ASC';
241                 $sSQL .= ' LIMIT 1';
242                 Debug::printSQL($sSQL);
243
244                 $aPlaceNode = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
245                 Debug::printVar('Nearest place node', $aPlaceNode);
246                 if ($aPlaceNode) {
247                     return $aPlaceNode;
248                 }
249             }
250         }
251         return $aPoly;
252     }
253
254
255     public function lookup($fLat, $fLon, $bDoInterpolation = true)
256     {
257         return $this->lookupPoint(
258             'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)',
259             $bDoInterpolation
260         );
261     }
262
263     public function lookupPoint($sPointSQL, $bDoInterpolation = true)
264     {
265         Debug::newFunction('lookupPoint');
266         // Find the nearest point
267         $fSearchDiam = 0.006;
268         $oResult = null;
269         $aPlace = null;
270
271         // for POI or street level
272         if ($this->iMaxRank >= 26) {
273             // starts if the search is on POI or street level,
274             // searches for the nearest POI or street,
275             // if a street is found and a POI is searched for,
276             // the nearest POI which the found street is a parent of is chosen.
277             $sSQL = 'select place_id,parent_place_id,rank_address,country_code,';
278             $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
279             $sSQL .= ' FROM ';
280             $sSQL .= ' placex';
281             $sSQL .= '   WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
282             $sSQL .= '   AND';
283             $sSQL .= ' rank_address between 26 and '.$this->iMaxRank;
284             $sSQL .= ' and (name is not null or housenumber is not null';
285             $sSQL .= ' or rank_address between 26 and 27)';
286             $sSQL .= ' and (rank_address between 26 and 27';
287             $sSQL .= '      or ST_GeometryType(geometry) != \'ST_LineString\')';
288             $sSQL .= ' and class not in (\'boundary\')';
289             $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
290             $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
291             $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
292             $sSQL .= ' ORDER BY distance ASC limit 1';
293             Debug::printSQL($sSQL);
294
295             $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine closest place.');
296
297             Debug::printVar('POI/street level result', $aPlace);
298             if ($aPlace) {
299                 $iPlaceID = $aPlace['place_id'];
300                 $oResult = new Result($iPlaceID);
301                 $iRankAddress = $aPlace['rank_address'];
302             }
303
304             if ($aPlace) {
305                 // if street and maxrank > streetlevel
306                 if ($iRankAddress <= 27 && $this->iMaxRank > 27) {
307                     // find the closest object (up to a certain radius) of which the street is a parent of
308                     $sSQL = ' select place_id,';
309                     $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
310                     $sSQL .= ' FROM ';
311                     $sSQL .= ' placex';
312                     // radius ?
313                     $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, 0.001)';
314                     $sSQL .= ' AND parent_place_id = '.$iPlaceID;
315                     $sSQL .= ' and rank_address > 28';
316                     $sSQL .= ' and ST_GeometryType(geometry) != \'ST_LineString\'';
317                     $sSQL .= ' and (name is not null or housenumber is not null)';
318                     $sSQL .= ' and class not in (\'boundary\')';
319                     $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
320                     $sSQL .= ' ORDER BY distance ASC limit 1';
321                     Debug::printSQL($sSQL);
322
323                     $aStreet = $this->oDB->getRow($sSQL, null, 'Could not determine closest place.');
324                     Debug::printVar('Closest POI result', $aStreet);
325
326                     if ($aStreet) {
327                         $aPlace = $aStreet;
328                         $oResult = new Result($aStreet['place_id']);
329                         $iRankAddress = 30;
330                     }
331                 }
332
333                   // In the US we can check TIGER data for nearest housenumber
334                 if (CONST_Use_US_Tiger_Data
335                     && $iRankAddress <= 27
336                     && $aPlace['country_code'] == 'us'
337                     && $this->iMaxRank >= 28
338                 ) {
339                     $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search,';
340                     $sSQL .= '      (endnumber - startnumber) * ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fhnr,';
341                     $sSQL .= '      startnumber, endnumber, step,';
342                     $sSQL .= '      ST_Distance('.$sPointSQL.', linegeo) as distance';
343                     $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$oResult->iId;
344                     $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, 0.001)';
345                     $sSQL .= ' ORDER BY distance ASC limit 1';
346                     Debug::printSQL($sSQL);
347
348                     $aPlaceTiger = $this->oDB->getRow($sSQL, null, 'Could not determine closest Tiger place.');
349                     Debug::printVar('Tiger house number result', $aPlaceTiger);
350
351                     if ($aPlaceTiger) {
352                         $aPlace = $aPlaceTiger;
353                         $oResult = new Result($aPlaceTiger['place_id'], Result::TABLE_TIGER);
354                         $iRndNum = max(0, round($aPlaceTiger['fhnr'] / $aPlaceTiger['step']) * $aPlaceTiger['step']);
355                         $oResult->iHouseNumber = $aPlaceTiger['startnumber'] + $iRndNum;
356                         if ($oResult->iHouseNumber > $aPlaceTiger['endnumber']) {
357                             $oResult->iHouseNumber = $aPlaceTiger['endnumber'];
358                         }
359                         $iRankAddress = 30;
360                     }
361                 }
362             }
363
364             if ($bDoInterpolation && $this->iMaxRank >= 30) {
365                 $fDistance = $fSearchDiam;
366                 if ($aPlace) {
367                     // We can't reliably go from the closest street to an
368                     // interpolation line because the closest interpolation
369                     // may have a different street segments as a parent.
370                     // Therefore allow an interpolation line to take precedence
371                     // even when the street is closer.
372                     $fDistance = $iRankAddress < 28 ? 0.001 : $aPlace['distance'];
373                 }
374
375                 $aHouse = $this->lookupInterpolation($sPointSQL, $fDistance);
376                 Debug::printVar('Interpolation result', $aPlace);
377
378                 if ($aHouse) {
379                     $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
380                     $iRndNum = max(0, round($aHouse['fhnr'] / $aHouse['step']) * $aHouse['step']);
381                     $oResult->iHouseNumber = $aHouse['startnumber'] + $iRndNum;
382                     if ($oResult->iHouseNumber > $aHouse['endnumber']) {
383                         $oResult->iHouseNumber = $aHouse['endnumber'];
384                     }
385                     $aPlace = $aHouse;
386                 }
387             }
388
389             if (!$aPlace) {
390                 // if no POI or street is found ...
391                 $oResult = $this->lookupLargeArea($sPointSQL, 25);
392             }
393         } else {
394             // lower than street level ($iMaxRank < 26 )
395             $oResult = $this->lookupLargeArea($sPointSQL, $this->iMaxRank);
396         }
397
398         Debug::printVar('Final result', $oResult);
399         return $oResult;
400     }
401 }