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