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