]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/ReverseGeocode.php
correctly handle single-point interpolations in reverse
[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 / Village
44                       13 => 18,
45                       14 => 22, // Suburb
46                       15 => 22,
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 .= ' ORDER BY distance ASC limit 1';
76         Debug::printSQL($sSQL);
77
78         return $this->oDB->getRow(
79             $sSQL,
80             null,
81             'Could not determine closest housenumber on an osm interpolation line.'
82         );
83     }
84
85     protected function lookupLargeArea($sPointSQL, $iMaxRank)
86     {
87         if ($iMaxRank > 4) {
88             $aPlace = $this->lookupPolygon($sPointSQL, $iMaxRank);
89             if ($aPlace) {
90                 return new Result($aPlace['place_id']);
91             }
92         }
93
94         // If no polygon which contains the searchpoint is found,
95         // searches in the country_osm_grid table for a polygon.
96         return  $this->lookupInCountry($sPointSQL, $iMaxRank);
97     }
98
99     protected function lookupInCountry($sPointSQL, $iMaxRank)
100     {
101         Debug::newFunction('lookupInCountry');
102         // searches for polygon in table country_osm_grid which contains the searchpoint
103         // and searches for the nearest place node to the searchpoint in this polygon
104         $sSQL = 'SELECT country_code FROM country_osm_grid';
105         $sSQL .= ' WHERE ST_CONTAINS(geometry, '.$sPointSQL.') LIMIT 1';
106         Debug::printSQL($sSQL);
107
108         $sCountryCode = $this->oDB->getOne(
109             $sSQL,
110             null,
111             'Could not determine country polygon containing the point.'
112         );
113         Debug::printVar('Country code', $sCountryCode);
114
115         if ($sCountryCode) {
116             if ($iMaxRank > 4) {
117                 // look for place nodes with the given country code
118                 $sSQL = 'SELECT place_id FROM';
119                 $sSQL .= ' (SELECT place_id, rank_search,';
120                 $sSQL .= '         ST_distance('.$sPointSQL.', geometry) as distance';
121                 $sSQL .= ' FROM placex';
122                 $sSQL .= ' WHERE osm_type = \'N\'';
123                 $sSQL .= ' AND country_code = \''.$sCountryCode.'\'';
124                 $sSQL .= ' AND rank_search < 26 '; // needed to select right index
125                 $sSQL .= ' AND rank_search between 5 and ' .min(25, $iMaxRank);
126                 $sSQL .= ' AND class = \'place\' AND type != \'postcode\'';
127                 $sSQL .= ' AND name IS NOT NULL ';
128                 $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
129                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, 1.8)) p ';
130                 $sSQL .= 'WHERE distance <= reverse_place_diameter(rank_search)';
131                 $sSQL .= ' ORDER BY rank_search DESC, distance ASC';
132                 $sSQL .= ' LIMIT 1';
133                 Debug::printSQL($sSQL);
134
135                 $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
136                 Debug::printVar('Country node', $aPlace);
137
138                 if ($aPlace) {
139                     return new Result($aPlace['place_id']);
140                 }
141             }
142
143             // still nothing, then return the country object
144             $sSQL = 'SELECT place_id, ST_distance('.$sPointSQL.', centroid) as distance';
145             $sSQL .= ' FROM placex';
146             $sSQL .= ' WHERE country_code = \''.$sCountryCode.'\'';
147             $sSQL .= ' AND rank_search = 4 AND rank_address = 4';
148             $sSQL .= ' AND class in (\'boundary\',  \'place\')';
149             $sSQL .= ' AND linked_place_id is null';
150             $sSQL .= ' ORDER BY distance ASC';
151             Debug::printSQL($sSQL);
152
153             $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
154             Debug::printVar('Country place', $aPlace);
155             if ($aPlace) {
156                 return new Result($aPlace['place_id']);
157             }
158         }
159
160         return null;
161     }
162
163     /**
164      * Search for areas or nodes for areas or nodes between state and suburb level.
165      *
166      * @param string $sPointSQL Search point as SQL string.
167      * @param int    $iMaxRank  Maximum address rank of the feature.
168      *
169      * @return Record of the found feature or null.
170      *
171      * Searches first for polygon that contains the search point.
172      * If such a polygon is found, place nodes with a higher rank are
173      * searched inside the polygon.
174      */
175     protected function lookupPolygon($sPointSQL, $iMaxRank)
176     {
177         Debug::newFunction('lookupPolygon');
178         // polygon search begins at suburb-level
179         if ($iMaxRank > 25) {
180             $iMaxRank = 25;
181         }
182         // no polygon search over country-level
183         if ($iMaxRank < 5) {
184             $iMaxRank = 5;
185         }
186         // search for polygon
187         $sSQL = 'SELECT place_id, parent_place_id, rank_address, rank_search FROM';
188         $sSQL .= '(select place_id, parent_place_id, rank_address, rank_search, country_code, geometry';
189         $sSQL .= ' FROM placex';
190         $sSQL .= ' WHERE ST_GeometryType(geometry) in (\'ST_Polygon\', \'ST_MultiPolygon\')';
191         $sSQL .= ' AND rank_address Between 5 AND ' .$iMaxRank;
192         $sSQL .= ' AND geometry && '.$sPointSQL;
193         $sSQL .= ' AND type != \'postcode\' ';
194         $sSQL .= ' AND name is not null';
195         $sSQL .= ' AND indexed_status = 0 and linked_place_id is null';
196         $sSQL .= ' ORDER BY rank_address DESC LIMIT 50 ) as a';
197         $sSQL .= ' WHERE ST_CONTAINS(geometry, '.$sPointSQL.' )';
198         $sSQL .= ' ORDER BY rank_address DESC LIMIT 1';
199         Debug::printSQL($sSQL);
200
201         $aPoly = $this->oDB->getRow($sSQL, null, 'Could not determine polygon containing the point.');
202         Debug::printVar('Polygon result', $aPoly);
203
204         if ($aPoly) {
205         // if a polygon is found, search for placenodes begins ...
206             $iRankAddress = $aPoly['rank_address'];
207             $iRankSearch = $aPoly['rank_search'];
208             $iPlaceID = $aPoly['place_id'];
209
210             if ($iRankAddress != $iMaxRank) {
211                 $sSQL = 'SELECT place_id FROM ';
212                 $sSQL .= '(SELECT place_id, rank_search, country_code, geometry,';
213                 $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
214                 $sSQL .= ' FROM placex';
215                 $sSQL .= ' WHERE osm_type = \'N\'';
216                 // using rank_search because of a better differentiation
217                 // for place nodes at rank_address 16
218                 $sSQL .= ' AND rank_search > '.$iRankSearch;
219                 $sSQL .= ' AND rank_search <= '.$iMaxRank;
220                 $sSQL .= ' AND rank_search < 26 '; // needed to select right index
221                 $sSQL .= ' AND rank_address > 0';
222                 $sSQL .= ' AND class = \'place\'';
223                 $sSQL .= ' AND type != \'postcode\'';
224                 $sSQL .= ' AND name IS NOT NULL ';
225                 $sSQL .= ' AND indexed_status = 0 AND linked_place_id is null';
226                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, reverse_place_diameter('.$iRankSearch.'::smallint))';
227                 $sSQL .= ' ORDER BY distance ASC,';
228                 $sSQL .= ' rank_address DESC';
229                 $sSQL .= ' limit 500) as a';
230                 $sSQL .= ' WHERE ST_CONTAINS((SELECT geometry FROM placex WHERE place_id = '.$iPlaceID.'), geometry )';
231                 $sSQL .= ' AND distance <= reverse_place_diameter(rank_search)';
232                 $sSQL .= ' ORDER BY distance ASC, rank_search DESC';
233                 $sSQL .= ' LIMIT 1';
234                 Debug::printSQL($sSQL);
235
236                 $aPlaceNode = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
237                 Debug::printVar('Nearest place node', $aPlaceNode);
238                 if ($aPlaceNode) {
239                     return $aPlaceNode;
240                 }
241             }
242         }
243         return $aPoly;
244     }
245
246
247     public function lookup($fLat, $fLon, $bDoInterpolation = true)
248     {
249         return $this->lookupPoint(
250             'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)',
251             $bDoInterpolation
252         );
253     }
254
255     public function lookupPoint($sPointSQL, $bDoInterpolation = true)
256     {
257         Debug::newFunction('lookupPoint');
258         // Find the nearest point
259         $fSearchDiam = 0.006;
260         $oResult = null;
261         $aPlace = null;
262
263         // for POI or street level
264         if ($this->iMaxRank >= 26) {
265             // starts if the search is on POI or street level,
266             // searches for the nearest POI or street,
267             // if a street is found and a POI is searched for,
268             // the nearest POI which the found street is a parent of is choosen.
269             $sSQL = 'select place_id,parent_place_id,rank_address,country_code,';
270             $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
271             $sSQL .= ' FROM ';
272             $sSQL .= ' placex';
273             $sSQL .= '   WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
274             $sSQL .= '   AND';
275             $sSQL .= ' rank_address between 26 and '.$this->iMaxRank;
276             $sSQL .= ' and (name is not null or housenumber is not null';
277             $sSQL .= ' or rank_address between 26 and 27)';
278             $sSQL .= ' and (rank_address between 26 and 27';
279             $sSQL .= '      or ST_GeometryType(geometry) != \'ST_LineString\')';
280             $sSQL .= ' and class not in (\'boundary\')';
281             $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
282             $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
283             $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
284             $sSQL .= ' ORDER BY distance ASC limit 1';
285             Debug::printSQL($sSQL);
286
287             $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine closest place.');
288
289             Debug::printVar('POI/street level result', $aPlace);
290             if ($aPlace) {
291                 $iPlaceID = $aPlace['place_id'];
292                 $oResult = new Result($iPlaceID);
293                 $iRankAddress = $aPlace['rank_address'];
294             }
295
296             if ($aPlace) {
297                 // if street and maxrank > streetlevel
298                 if ($iRankAddress <= 27 && $this->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,';
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 ST_GeometryType(geometry) != \'ST_LineString\'';
309                     $sSQL .= ' and (name is not null or housenumber is not null)';
310                     $sSQL .= ' and class not in (\'boundary\')';
311                     $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
312                     $sSQL .= ' ORDER BY distance ASC limit 1';
313                     Debug::printSQL($sSQL);
314
315                     $aStreet = $this->oDB->getRow($sSQL, null, 'Could not determine closest place.');
316                     Debug::printVar('Closest POI result', $aStreet);
317
318                     if ($aStreet) {
319                         $aPlace = $aStreet;
320                         $oResult = new Result($aStreet['place_id']);
321                         $iRankAddress = 30;
322                     }
323                 }
324
325                   // In the US we can check TIGER data for nearest housenumber
326                 if (CONST_Use_US_Tiger_Data
327                     && $iRankAddress <= 27
328                     && $aPlace['country_code'] == 'us'
329                     && $this->iMaxRank >= 28
330                 ) {
331                     $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search,';
332                     $sSQL .= '      (endnumber - startnumber) * ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fhnr,';
333                     $sSQL .= '      startnumber, endnumber, step,';
334                     $sSQL .= '      ST_Distance('.$sPointSQL.', linegeo) as distance';
335                     $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$oResult->iId;
336                     $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, 0.001)';
337                     $sSQL .= ' ORDER BY distance ASC limit 1';
338                     Debug::printSQL($sSQL);
339
340                     $aPlaceTiger = $this->oDB->getRow($sSQL, null, 'Could not determine closest Tiger place.');
341                     Debug::printVar('Tiger house number result', $aPlaceTiger);
342
343                     if ($aPlaceTiger) {
344                         $aPlace = $aPlaceTiger;
345                         $oResult = new Result($aPlaceTiger['place_id'], Result::TABLE_TIGER);
346                         $iRndNum = max(0, round($aPlaceTiger['fhnr'] / $aPlaceTiger['step']) * $aPlaceTiger['step']);
347                         $oResult->iHouseNumber = $aPlaceTiger['startnumber'] + $iRndNum;
348                         if ($oResult->iHouseNumber > $aPlaceTiger['endnumber']) {
349                             $oResult->iHouseNumber = $aPlaceTiger['endnumber'];
350                         }
351                         $iRankAddress = 30;
352                     }
353                 }
354             }
355
356             if ($bDoInterpolation && $this->iMaxRank >= 30) {
357                 $fDistance = $fSearchDiam;
358                 if ($aPlace) {
359                     // We can't reliably go from the closest street to an
360                     // interpolation line because the closest interpolation
361                     // may have a different street segments as a parent.
362                     // Therefore allow an interpolation line to take precendence
363                     // even when the street is closer.
364                     $fDistance = $iRankAddress < 28 ? 0.001 : $aPlace['distance'];
365                 }
366
367                 $aHouse = $this->lookupInterpolation($sPointSQL, $fDistance);
368                 Debug::printVar('Interpolation result', $aPlace);
369
370                 if ($aHouse) {
371                     $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
372                     $iRndNum = max(0, round($aHouse['fhnr'] / $aHouse['step']) * $aHouse['step']);
373                     $oResult->iHouseNumber = $aHouse['startnumber'] + $iRndNum;
374                     if ($oResult->iHouseNumber > $aHouse['endnumber']) {
375                         $oResult->iHouseNumber = $aHouse['endnumber'];
376                     }
377                     $aPlace = $aHouse;
378                 }
379             }
380
381             if (!$aPlace) {
382                 // if no POI or street is found ...
383                 $oResult = $this->lookupLargeArea($sPointSQL, 25);
384             }
385         } else {
386             // lower than street level ($iMaxRank < 26 )
387             $oResult = $this->lookupLargeArea($sPointSQL, $this->iMaxRank);
388         }
389
390         Debug::printVar('Final result', $oResult);
391         return $oResult;
392     }
393 }