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