]> git.openstreetmap.org Git - nominatim.git/blob - lib/ReverseGeocode.php
remove duplicate reverse geocoding code
[nominatim.git] / lib / ReverseGeocode.php
1 <?php
2         class ReverseGeocode
3         {
4                 protected $oDB;
5
6                 protected $fLat;
7                 protected $fLon;
8                 protected $iMaxRank = 28;
9
10                 protected $aLangPrefOrder = array();
11
12                 protected $bIncludePolygonAsPoints = false;
13                 protected $bIncludePolygonAsText = false;
14                 protected $bIncludePolygonAsGeoJSON = false;
15                 protected $bIncludePolygonAsKML = false;
16                 protected $bIncludePolygonAsSVG = false;
17                 protected $fPolygonSimplificationThreshold = 0.0;
18
19
20                 function ReverseGeocode(&$oDB)
21                 {
22                         $this->oDB =& $oDB;
23                 }
24
25                 function setLanguagePreference($aLangPref)
26                 {
27                         $this->aLangPrefOrder = $aLangPref;
28                 }
29
30                 function setLatLon($fLat, $fLon)
31                 {
32                         $this->fLat = (float)$fLat;
33                         $this->fLon = (float)$fLon;
34                 }
35
36                 function setRank($iRank)
37                 {
38                         $this->iMaxRank = $iRank;
39                 }
40
41                 function setZoom($iZoom)
42                 {
43                         // Zoom to rank, this could probably be calculated but a lookup gives fine control
44                         $aZoomRank = array(
45                                 0 => 2, // Continent / Sea
46                                 1 => 2,
47                                 2 => 2,
48                                 3 => 4, // Country
49                                 4 => 4,
50                                 5 => 8, // State
51                                 6 => 10, // Region
52                                 7 => 10,
53                                 8 => 12, // County
54                                 9 => 12,
55                                 10 => 17, // City
56                                 11 => 17,
57                                 12 => 18, // Town / Village
58                                 13 => 18,
59                                 14 => 22, // Suburb
60                                 15 => 22,
61                                 16 => 26, // Street, TODO: major street?
62                                 17 => 26,
63                                 18 => 30, // or >, Building
64                                 19 => 30, // or >, Building
65                                 );
66                         $this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
67                 }
68
69                                 function setIncludePolygonAsPoints($b = true)
70                 {
71                         $this->bIncludePolygonAsPoints = $b;
72                 }
73
74                 function getIncludePolygonAsPoints()
75                 {
76                         return $this->bIncludePolygonAsPoints;
77                 }
78
79                 function setIncludePolygonAsText($b = true)
80                 {
81                         $this->bIncludePolygonAsText = $b;
82                 }
83
84                 function getIncludePolygonAsText()
85                 {
86                         return $this->bIncludePolygonAsText;
87                 }
88
89                 function setIncludePolygonAsGeoJSON($b = true)
90                 {
91                         $this->bIncludePolygonAsGeoJSON = $b;
92                 }
93
94                 function setIncludePolygonAsKML($b = true)
95                 {
96                         $this->bIncludePolygonAsKML = $b;
97                 }
98
99                 function setIncludePolygonAsSVG($b = true)
100                 {
101                         $this->bIncludePolygonAsSVG = $b;
102                 }
103
104                 function setPolygonSimplificationThreshold($f)
105                 {
106                         $this->fPolygonSimplificationThreshold = $f;
107                 }
108
109                 // returns { place_id =>, type => '(osm|tiger)' }
110                 // fails if no place was found
111                 function lookup($bDoInterpolation = true)
112                 {
113                         $sPointSQL = 'ST_SetSRID(ST_Point('.$this->fLon.','.$this->fLat.'),4326)';
114                         $iMaxRank = $this->iMaxRank;
115                         $iMaxRank_orig = $this->iMaxRank;
116
117                         // Find the nearest point
118                         $fSearchDiam = 0.0004;
119                         $iPlaceID = null;
120                         $aArea = false;
121                         $fMaxAreaDistance = 1;
122                         $bIsInUnitedStates = false;
123                         $bPlaceIsTiger = false;
124                         $bPlaceIsLine = false;
125                         while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
126                         {
127                                 $fSearchDiam = $fSearchDiam * 2;
128
129                                 // If we have to expand the search area by a large amount then we need a larger feature
130                                 // then there is a limit to how small the feature should be
131                                 if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4;
132                                 if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8;
133                                 if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10;
134                                 if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12;
135                                 if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17;
136                                 if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18;
137                                 if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22;
138                                 if ($fSearchDiam > 0.001 && $iMaxRank > 26) $iMaxRank = 26;
139
140                                 $sSQL = 'select place_id,parent_place_id,rank_search,calculated_country_code';
141                                 $sSQL .= ' FROM placex';
142                                 $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
143                                 $sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank;
144                                 $sSQL .= ' and (name is not null or housenumber is not null)';
145                                 $sSQL .= ' and class not in (\'waterway\',\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
146                                 $sSQL .= ' and indexed_status = 0 ';
147                                 $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
148                                 $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
149                                 $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
150                                 if (CONST_Debug) var_dump($sSQL);
151                                 $aPlace = chksql($this->oDB->getRow($sSQL),
152                                                  "Could not determine closest place.");
153                                 $iPlaceID = $aPlace['place_id'];
154                                 $iParentPlaceID = $aPlace['parent_place_id'];
155                                 $bIsInUnitedStates = ($aPlace['calculated_country_code'] == 'us');
156                         }
157                         // if a street or house was found, look in interpolation lines table
158                         if ($bDoInterpolation && $iMaxRank_orig >= 28 && $aPlace && $aPlace['rank_search'] >= 26)
159                         {
160                                 // if a house was found, search the interpolation line that is at least as close as the house
161                                 $sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
162                                 $sSQL .= ' FROM location_property_osmline';
163                                 $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
164                                 $sSQL .= ' and indexed_status = 0 ';
165                                 $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
166                                 
167                                 if (CONST_Debug)
168                                 {
169                                         $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
170                                         var_dump($sSQL);
171
172                                         $aAllHouses = chksql($this->oDB->getAll($sSQL));
173                                         foreach($aAllHouses as $i)
174                                         {
175                                                 echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
176                                         }
177                                 }
178                                 $aPlaceLine = chksql($this->oDB->getRow($sSQL),
179                                                      "Could not determine closest housenumber on an osm interpolation line.");
180                                 if ($aPlaceLine)
181                                 {
182                                         if (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine);
183                                         if ($aPlace['rank_search'] == 30)
184                                         {
185                                                 // if a house was already found in placex, we have to find out, 
186                                                 // if the placex house or the interpolated house are closer to the searched point
187                                                 // distance between point and placex house
188                                                 $sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID;
189                                                 $aDistancePlacex = chksql($this->oDB->getRow($sSQL),
190                                                                           "Could not determine distance between searched point and placex house.");
191                                                 $fDistancePlacex = $aDistancePlacex['distance'];
192                                                 // distance between point and interpolated house (fraction on interpolation line)
193                                                 $sSQL = 'SELECT ST_distance('.$sPointSQL.', ST_LineInterpolatePoint(linegeo, '.$aPlaceLine['fraction'].')) as distance';
194                                                 $sSQL .= ' FROM location_property_osmline WHERE place_id = '.$aPlaceLine['place_id'];
195                                                 $aDistanceInterpolation = chksql($this->oDB->getRow($sSQL),
196                                                                                  "Could not determine distance between searched point and interpolated house.");
197                                                 $fDistanceInterpolation = $aDistanceInterpolation['distance'];
198                                                 if ($fDistanceInterpolation < $fDistancePlacex)
199                                                 {
200                                                         // interpolation is closer to point than placex house
201                                                         $bPlaceIsLine = true;
202                                                         $aPlace = $aPlaceLine;
203                                                         $iPlaceID = $aPlaceLine['place_id'];
204                                                         $iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
205                                                         $fFraction = $aPlaceLine['fraction'];
206                                                         $iMaxRank = 30;
207                                                 }
208                                                 // else: nothing to do, take placex house from above
209                                         }
210                                         else
211                                         {
212                                                 $bPlaceIsLine = true;
213                                                 $aPlace = $aPlaceLine;
214                                                 $iPlaceID = $aPlaceLine['place_id'];
215                                                 $iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
216                                                 $fFraction = $aPlaceLine['fraction'];
217                                                 $iMaxRank = 30;
218                                         }
219                                 }
220                         }
221                         
222                         // Only street found? If it's in the US we can check TIGER data for nearest housenumber
223                         if (CONST_Use_US_Tiger_Data && $bDoInterpolation && $bIsInUnitedStates && $iMaxRank_orig >= 28 && $iPlaceID && ($aPlace['rank_search'] == 26 || $aPlace['rank_search'] == 27 ))
224                         {
225                                 $fSearchDiam = 0.001;
226                                 $sSQL = 'SELECT place_id,parent_place_id,30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
227                                 //if (CONST_Debug) { $sSQL .= ', housenumber, ST_distance('.$sPointSQL.', centroid) as distance, st_y(centroid) as lat, st_x(centroid) as lon'; }
228                                 $sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$iPlaceID;
229                                 $sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';  //no centroid anymore in Tiger data, now we have lines
230                                 $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
231
232                                 if (CONST_Debug)
233                                 {
234                                         $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
235                                         var_dump($sSQL);
236
237                                         $aAllHouses = chksql($this->oDB->getAll($sSQL));
238                                         foreach($aAllHouses as $i)
239                                         {
240                                                 echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
241                                         }
242                                 }
243
244                                 $aPlaceTiger = chksql($this->oDB->getRow($sSQL),
245                                                       "Could not determine closest Tiger place.");
246                                 if ($aPlaceTiger)
247                                 {
248                                         if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
249                                         $bPlaceIsTiger = true;
250                                         $aPlace = $aPlaceTiger;
251                                         $iPlaceID = $aPlaceTiger['place_id'];
252                                         $iParentPlaceID = $aPlaceTiger['parent_place_id']; // the street
253                                         $fFraction = $aPlaceTiger['fraction'];
254                                         $iMaxRank = 30;
255                                 }
256                         }
257
258                         // The point we found might be too small - use the address to find what it is a child of
259                         if ($iPlaceID && $iMaxRank < 28)
260                         {
261                                 if (($aPlace['rank_search'] > 28 || $bPlaceIsTiger || $bPlaceIsLine) && $iParentPlaceID)
262                                 {
263                                         $iPlaceID = $iParentPlaceID;
264                                 }
265                                 $sSQL  = 'select address_place_id';
266                                 $sSQL .= ' FROM place_addressline';
267                                 $sSQL .= " WHERE place_id = $iPlaceID";
268                                 $sSQL .= " ORDER BY abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc";
269                                 $sSQL .= ' LIMIT 1';
270                                 $iPlaceID = chksql($this->oDB->getOne($sSQL),
271                                                    "Could not get parent for place.");
272                                 if (!$iPlaceID)
273                                 {
274                                         $iPlaceID = $aPlace['place_id'];
275                                 }
276                         }
277                         return array('place_id' => $iPlaceID,
278                                                 'type' => $bPlaceIsTiger ? 'tiger' : ($bPlaceIsLine ? 'interpolation' : 'osm'),
279                                                 'fraction' => ($bPlaceIsTiger || $bPlaceIsLine) ? $fFraction : -1);
280                 }
281                 
282         }
283 ?>