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