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