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