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