]> git.openstreetmap.org Git - nominatim.git/blob - lib/ReverseGeocode.php
9b43a3e38cdd8d2aabd8c5391b0aeee90898631b
[nominatim.git] / lib / ReverseGeocode.php
1 <?php
2
3 namespace Nominatim;
4
5 class ReverseGeocode
6 {
7     protected $oDB;
8     protected $iMaxRank = 28;
9
10
11     public function __construct(&$oDB)
12     {
13         $this->oDB =& $oDB;
14     }
15
16
17     public function setZoom($iZoom)
18     {
19         // Zoom to rank, this could probably be calculated but a lookup gives fine control
20         $aZoomRank = array(
21                       0 => 2, // Continent / Sea
22                       1 => 2,
23                       2 => 2,
24                       3 => 4, // Country
25                       4 => 4,
26                       5 => 8, // State
27                       6 => 10, // Region
28                       7 => 10,
29                       8 => 12, // County
30                       9 => 12,
31                       10 => 17, // City
32                       11 => 17,
33                       12 => 18, // Town / Village
34                       13 => 18,
35                       14 => 22, // Suburb
36                       15 => 22,
37                       16 => 26, // Street, TODO: major street?
38                       17 => 26,
39                       18 => 30, // or >, Building
40                       19 => 30, // or >, Building
41                      );
42         $this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
43     }
44
45     /**
46      * Find the closest interpolation with the given search diameter.
47      *
48      * @param string $sPointSQL   Reverse geocoding point as SQL
49      * @param float  $fSearchDiam Search diameter
50      *
51      * @return Record of the interpolation or null.
52      */
53     protected function lookupInterpolation($sPointSQL, $fSearchDiam)
54     {
55         $sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search,';
56         $sSQL .= ' ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fraction';
57         $sSQL .= ' , ST_Distance(linegeo,'.$sPointSQL.') as distance';
58         $sSQL .= ' FROM location_property_osmline';
59         $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
60         $sSQL .= ' and indexed_status = 0 and startnumber is not NULL ';
61         $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
62
63         return chksql(
64             $this->oDB->getRow($sSQL),
65             "Could not determine closest housenumber on an osm interpolation line."
66         );
67     }
68
69     public function lookup($fLat, $fLon, $bDoInterpolation = true)
70     {
71         return $this->lookupPoint(
72             'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)',
73             $bDoInterpolation
74         );
75     }
76
77     /* lookup()
78      * returns { place_id =>, type => '(osm|tiger)' }
79      * fails if no place was found
80      */
81
82
83     public function lookupPoint($sPointSQL, $bDoInterpolation = true)
84     {
85         $iMaxRank = $this->iMaxRank;
86
87         // Find the nearest point
88         $fSearchDiam = 0.0004;
89         $iPlaceID = null;
90         $fMaxAreaDistance = 1;
91         $bIsInUnitedStates = false;
92         $bPlaceIsTiger = false;
93         $bPlaceIsLine = false;
94         while (!$iPlaceID && $fSearchDiam < $fMaxAreaDistance) {
95             $fSearchDiam = $fSearchDiam * 2;
96
97             // If we have to expand the search area by a large amount then we need a larger feature
98             // then there is a limit to how small the feature should be
99             if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4;
100             if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8;
101             if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10;
102             if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12;
103             if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17;
104             if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18;
105             if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22;
106             if ($fSearchDiam > 0.001 && $iMaxRank > 26) {
107                 // try with interpolations before continuing
108                 if ($bDoInterpolation) {
109                     // no house found, try with interpolations
110                     $aPlaceLine = $this->lookupInterpolation($sPointSQL, $fSearchDiam/2);
111
112                     if ($aPlaceLine) {
113                         // interpolation is closer to point than placex house
114                         $bPlaceIsLine = true;
115                         $aPlace = $aPlaceLine;
116                         $iPlaceID = $aPlaceLine['place_id'];
117                         $iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
118                         $fFraction = $aPlaceLine['fraction'];
119                         $iMaxRank = 30;
120
121                         break;
122                     }
123                 }
124                 // no interpolation found, continue search
125                 $iMaxRank = 26;
126             }
127
128             $sSQL = 'select place_id,parent_place_id,rank_search,country_code';
129             $sSQL .= ' FROM placex';
130             $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
131             $sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank;
132             $sSQL .= ' and (name is not null or housenumber is not null)';
133             $sSQL .= ' and class not in (\'waterway\',\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
134             $sSQL .= ' and indexed_status = 0 ';
135             $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
136             $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
137             $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
138             if (CONST_Debug) var_dump($sSQL);
139             $aPlace = chksql(
140                 $this->oDB->getRow($sSQL),
141                 "Could not determine closest place."
142             );
143             $iPlaceID = $aPlace['place_id'];
144             $iParentPlaceID = $aPlace['parent_place_id'];
145             $bIsInUnitedStates = ($aPlace['country_code'] == 'us');
146         }
147
148         // If a house was found make sure there isn't an interpolation line
149         // that is closer
150         if ($bDoInterpolation && !$bPlaceIsLine && $aPlace && $aPlace['rank_search'] == 30) {
151             // get the distance of the house to the search point
152             $sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry)';
153             $sSQL .= ' FROM placex as house WHERE house.place_id='.$iPlaceID;
154
155             $fDistancePlacex = chksql(
156                 $this->oDB->getOne($sSQL),
157                 "Could not determine distance between searched point and placex house."
158             );
159
160             // look for an interpolation that is closer
161             $aPlaceLine = $this->lookupInterpolation($sPointSQL, $fDistancePlacex);
162
163             if ($aPlaceLine && (float) $aPlaceLine['distance'] < (float) $fDistancePlacex) {
164                 // interpolation is closer to point than placex house
165                 $bPlaceIsLine = true;
166                 $aPlace = $aPlaceLine;
167                 $iPlaceID = $aPlaceLine['place_id'];
168                 $iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
169                 $fFraction = $aPlaceLine['fraction'];
170             }
171         }
172
173         // Only street found? If it's in the US we can check TIGER data for nearest housenumber
174         if (CONST_Use_US_Tiger_Data && $bDoInterpolation && $bIsInUnitedStates && $this->iMaxRank >= 28 && $iPlaceID && ($aPlace['rank_search'] == 26 || $aPlace['rank_search'] == 27 )) {
175             $fSearchDiam = 0.001;
176             $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search, ST_LineLocatePoint(linegeo,'.$sPointSQL.') as fraction';
177             //if (CONST_Debug) { $sSQL .= ', housenumber, ST_distance('.$sPointSQL.', centroid) as distance, st_y(centroid) as lat, st_x(centroid) as lon'; }
178             $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$iPlaceID;
179             $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';  //no centroid anymore in Tiger data, now we have lines
180             $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
181
182             if (CONST_Debug) {
183                 $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
184                 var_dump($sSQL);
185
186                 $aAllHouses = chksql($this->oDB->getAll($sSQL));
187                 foreach ($aAllHouses as $i) {
188                     echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
189                 }
190             }
191
192             $aPlaceTiger = chksql(
193                 $this->oDB->getRow($sSQL),
194                 "Could not determine closest Tiger place."
195             );
196             if ($aPlaceTiger) {
197                 if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
198                 $bPlaceIsTiger = true;
199                 $aPlace = $aPlaceTiger;
200                 $iPlaceID = $aPlaceTiger['place_id'];
201                 $iParentPlaceID = $aPlaceTiger['parent_place_id']; // the street
202                 $fFraction = $aPlaceTiger['fraction'];
203                 $iMaxRank = 30;
204             }
205         }
206
207         // The point we found might be too small - use the address to find what it is a child of
208         if ($iPlaceID && $iMaxRank < 28) {
209             if (($aPlace['rank_search'] > 28 || $bPlaceIsTiger || $bPlaceIsLine) && $iParentPlaceID) {
210                 $iPlaceID = $iParentPlaceID;
211                 $bPlaceIsLine = false;
212                 $bPlaceIsTiger = false;
213             }
214             $sSQL  = 'select address_place_id';
215             $sSQL .= ' FROM place_addressline';
216             $sSQL .= " WHERE place_id = $iPlaceID";
217             $sSQL .= " ORDER BY abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc";
218             $sSQL .= ' LIMIT 1';
219             $iPlaceID = chksql($this->oDB->getOne($sSQL), "Could not get parent for place.");
220             if (!$iPlaceID) {
221                 $iPlaceID = $aPlace['place_id'];
222             }
223         }
224         return array(
225                 'place_id' => $iPlaceID,
226                 'type' => $bPlaceIsTiger ? 'tiger' : ($bPlaceIsLine ? 'interpolation' : 'osm'),
227                 'fraction' => ($bPlaceIsTiger || $bPlaceIsLine) ? $fFraction : -1
228                );
229     }
230 }