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