]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/ReverseGeocode.php
remove unused functions
[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) {
169             $iMaxRank = 25;
170         }
171         // no polygon search over country-level
172         if ($iMaxRank < 5) {
173             $iMaxRank = 5;
174         }
175         // search for polygon
176         $sSQL = 'SELECT place_id, parent_place_id, rank_address, rank_search FROM';
177         $sSQL .= '(select place_id, parent_place_id, rank_address, rank_search, country_code, geometry';
178         $sSQL .= ' FROM placex';
179         $sSQL .= ' WHERE ST_GeometryType(geometry) in (\'ST_Polygon\', \'ST_MultiPolygon\')';
180         $sSQL .= ' AND rank_address Between 5 AND ' .$iMaxRank;
181         $sSQL .= ' AND geometry && '.$sPointSQL;
182         $sSQL .= ' AND type != \'postcode\' ';
183         $sSQL .= ' AND name is not null';
184         $sSQL .= ' AND indexed_status = 0 and linked_place_id is null';
185         $sSQL .= ' ORDER BY rank_address DESC LIMIT 50 ) as a';
186         $sSQL .= ' WHERE ST_CONTAINS(geometry, '.$sPointSQL.' )';
187         $sSQL .= ' ORDER BY rank_address DESC LIMIT 1';
188         Debug::printSQL($sSQL);
189
190         $aPoly = $this->oDB->getRow($sSQL, null, 'Could not determine polygon containing the point.');
191         Debug::printVar('Polygon result', $aPoly);
192
193         if ($aPoly) {
194         // if a polygon is found, search for placenodes begins ...
195             $iRankAddress = $aPoly['rank_address'];
196             $iRankSearch = $aPoly['rank_search'];
197             $iPlaceID = $aPoly['place_id'];
198
199             if ($iRankAddress != $iMaxRank) {
200                 $sSQL = 'SELECT place_id FROM ';
201                 $sSQL .= '(SELECT place_id, rank_search, country_code, geometry,';
202                 $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
203                 $sSQL .= ' FROM placex';
204                 $sSQL .= ' WHERE osm_type = \'N\'';
205                 // using rank_search because of a better differentiation
206                 // for place nodes at rank_address 16
207                 $sSQL .= ' AND rank_search > '.$iRankSearch;
208                 $sSQL .= ' AND rank_search <= '.$iMaxRank;
209                 $sSQL .= ' AND rank_address > 0';
210                 $sSQL .= ' AND class = \'place\'';
211                 $sSQL .= ' AND type != \'postcode\'';
212                 $sSQL .= ' AND name IS NOT NULL ';
213                 $sSQL .= ' AND indexed_status = 0 AND linked_place_id is null';
214                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', geometry, reverse_place_diameter('.$iRankSearch.'::smallint))';
215                 $sSQL .= ' ORDER BY distance ASC,';
216                 $sSQL .= ' rank_address DESC';
217                 $sSQL .= ' limit 500) as a';
218                 $sSQL .= ' WHERE ST_CONTAINS((SELECT geometry FROM placex WHERE place_id = '.$iPlaceID.'), geometry )';
219                 $sSQL .= ' AND distance <= reverse_place_diameter(rank_search)';
220                 $sSQL .= ' ORDER BY distance ASC, rank_search DESC';
221                 $sSQL .= ' LIMIT 1';
222                 Debug::printSQL($sSQL);
223
224                 $aPlaceNode = $this->oDB->getRow($sSQL, null, 'Could not determine place node.');
225                 Debug::printVar('Nearest place node', $aPlaceNode);
226                 if ($aPlaceNode) {
227                     return $aPlaceNode;
228                 }
229             }
230         }
231         return $aPoly;
232     }
233
234
235     public function lookup($fLat, $fLon, $bDoInterpolation = true)
236     {
237         return $this->lookupPoint(
238             'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)',
239             $bDoInterpolation
240         );
241     }
242
243     public function lookupPoint($sPointSQL, $bDoInterpolation = true)
244     {
245         Debug::newFunction('lookupPoint');
246         // starts if the search is on POI or street level,
247         // searches for the nearest POI or street,
248         // if a street is found and a POI is searched for,
249         // the nearest POI which the found street is a parent of is choosen.
250         $iMaxRank = $this->iMaxRank;
251
252         // Find the nearest point
253         $fSearchDiam = 0.006;
254         $oResult = null;
255         $aPlace = null;
256
257         // for POI or street level
258         if ($iMaxRank >= 26) {
259             $sSQL = 'select place_id,parent_place_id,rank_address,country_code,';
260             $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
261             $sSQL .= ' FROM ';
262             $sSQL .= ' placex';
263             $sSQL .= '   WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
264             $sSQL .= '   AND';
265             $sSQL .= ' rank_address between 26 and '.$iMaxRank;
266             $sSQL .= ' and (name is not null or housenumber is not null';
267             $sSQL .= ' or rank_address between 26 and 27)';
268             $sSQL .= ' and (rank_address between 26 and 27';
269             $sSQL .= '      or ST_GeometryType(geometry) != \'ST_LineString\')';
270             $sSQL .= ' and class not in (\'boundary\')';
271             $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
272             $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
273             $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
274             $sSQL .= ' ORDER BY distance ASC limit 1';
275             Debug::printSQL($sSQL);
276
277             $aPlace = $this->oDB->getRow($sSQL, null, 'Could not determine closest place.');
278
279             Debug::printVar('POI/street level result', $aPlace);
280             if ($aPlace) {
281                 $iPlaceID = $aPlace['place_id'];
282                 $oResult = new Result($iPlaceID);
283                 $iRankAddress = $aPlace['rank_address'];
284             }
285
286             if ($aPlace) {
287                 // if street and maxrank > streetlevel
288                 if ($iRankAddress <= 27 && $iMaxRank > 27) {
289                     // find the closest object (up to a certain radius) of which the street is a parent of
290                     $sSQL = ' select place_id,';
291                     $sSQL .= ' ST_distance('.$sPointSQL.', geometry) as distance';
292                     $sSQL .= ' FROM ';
293                     $sSQL .= ' placex';
294                     // radius ?
295                     $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, 0.001)';
296                     $sSQL .= ' AND parent_place_id = '.$iPlaceID;
297                     $sSQL .= ' and rank_address > 28';
298                     $sSQL .= ' and ST_GeometryType(geometry) != \'ST_LineString\'';
299                     $sSQL .= ' and (name is not null or housenumber is not null)';
300                     $sSQL .= ' and class not in (\'boundary\')';
301                     $sSQL .= ' and indexed_status = 0 and linked_place_id is null';
302                     $sSQL .= ' ORDER BY distance ASC limit 1';
303                     Debug::printSQL($sSQL);
304
305                     $aStreet = $this->oDB->getRow($sSQL, null, 'Could not determine closest place.');
306                     Debug::printVar('Closest POI result', $aStreet);
307
308                     if ($aStreet) {
309                         $aPlace = $aStreet;
310                         $oResult = new Result($aStreet['place_id']);
311                         $iRankAddress = 30;
312                     }
313                 }
314
315                   // In the US we can check TIGER data for nearest housenumber
316                 if (CONST_Use_US_Tiger_Data
317                     && $iRankAddress <= 27
318                     && $aPlace['country_code'] == 'us'
319                     && $this->iMaxRank >= 28
320                 ) {
321                     $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search,';
322                     $sSQL .= 'ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fraction,';
323                     $sSQL .= 'ST_distance('.$sPointSQL.', linegeo) as distance,';
324                     $sSQL .= 'startnumber,endnumber,interpolationtype';
325                     $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$oResult->iId;
326                     $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, 0.001)';
327                     $sSQL .= ' ORDER BY distance ASC limit 1';
328                     Debug::printSQL($sSQL);
329
330                     $aPlaceTiger = $this->oDB->getRow($sSQL, null, 'Could not determine closest Tiger place.');
331                     Debug::printVar('Tiger house number result', $aPlaceTiger);
332
333                     if ($aPlaceTiger) {
334                         $aPlace = $aPlaceTiger;
335                         $oResult = new Result($aPlaceTiger['place_id'], Result::TABLE_TIGER);
336                         $oResult->iHouseNumber = closestHouseNumber($aPlaceTiger);
337                         $iRankAddress = 30;
338                     }
339                 }
340             }
341
342             if ($bDoInterpolation && $iMaxRank >= 30) {
343                 $fDistance = $fSearchDiam;
344                 if ($aPlace) {
345                     // We can't reliably go from the closest street to an
346                     // interpolation line because the closest interpolation
347                     // may have a different street segments as a parent.
348                     // Therefore allow an interpolation line to take precendence
349                     // even when the street is closer.
350                     $fDistance = $iRankAddress < 28 ? 0.001 : $aPlace['distance'];
351                 }
352
353                 $aHouse = $this->lookupInterpolation($sPointSQL, $fDistance);
354                 Debug::printVar('Interpolation result', $aPlace);
355
356                 if ($aHouse) {
357                     $oResult = new Result($aHouse['place_id'], Result::TABLE_OSMLINE);
358                     $oResult->iHouseNumber = closestHouseNumber($aHouse);
359                     $aPlace = $aHouse;
360                 }
361             }
362
363             if (!$aPlace) {
364                 // if no POI or street is found ...
365                 $oResult = $this->lookupLargeArea($sPointSQL, 25);
366             }
367         } else {
368             // lower than street level ($iMaxRank < 26 )
369             $oResult = $this->lookupLargeArea($sPointSQL, $iMaxRank);
370         }
371
372         Debug::printVar('Final result', $oResult);
373         return $oResult;
374     }
375 }