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