]> git.openstreetmap.org Git - nominatim.git/blob - website/reverse.php
Updated reverse geocoding to improve handling of zoom=0
[nominatim.git] / website / reverse.php
1 <?php
2         require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3         require_once(CONST_BasePath.'/lib/log.php');
4
5     if (preg_match(CONST_BlockedUserAgents, $_SERVER["HTTP_USER_AGENT"]) > 0)
6     {
7         $fLoadAvg = getLoadAverage();
8         if ($fLoadAvg >= CONST_BlockReverseMaxLoad) {
9             header('HTTP/1.0 403 Forbidden');
10             header('Content-type: text/html; charset=utf-8');
11                 echo "<html><body><h1>App temporarily blocked</h1>";
12             echo "Your application has been temporarily blocked from the OpenStreetMap Nominatim ";
13             echo "geolocation service due to high server load.";
14             echo "\n</body></html>\n";
15             exit;
16         }
17
18     }
19
20
21         if (strpos(CONST_BulkUserIPs, ','.$_SERVER["REMOTE_ADDR"].',') !== false)
22         {
23                 $fLoadAvg = getLoadAverage();
24                 if ($fLoadAvg > 2) sleep(60);
25                 if ($fLoadAvg > 4) sleep(120);
26                 if ($fLoadAvg > 6)
27                 {
28                         echo "Bulk User: Temporary block due to high server load\n";
29                         exit;
30                 }
31         }
32
33         $oDB =& getDB();
34         ini_set('memory_limit', '200M');
35
36         // Format for output
37         $sOutputFormat = 'xml';
38         if (isset($_GET['format']) && ($_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
39         {
40                 $sOutputFormat = $_GET['format'];
41         }
42
43         // Show address breakdown
44         $bShowAddressDetails = true;
45         if (isset($_GET['addressdetails'])) $bShowAddressDetails = (bool)$_GET['addressdetails'];
46
47         // Prefered language
48         $aLangPrefOrder = getPrefferedLangauges();
49         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
50
51         $hLog = logStart($oDB, 'reverse', $_SERVER['QUERY_STRING'], $aLangPrefOrder);
52
53         if (isset($_GET['osm_type']) && isset($_GET['osm_id']) && (int)$_GET['osm_id'] && ($_GET['osm_type'] == 'N' || $_GET['osm_type'] == 'W' || $_GET['osm_type'] == 'R'))
54         {
55                 $iPlaceID = $oDB->getOne("select place_id from placex where osm_type = '".$_GET['osm_type']."' and osm_id = ".(int)$_GET['osm_id']." order by type = 'postcode' asc");
56                 if (!$iPlaceID) $sError = 'OSM ID Not Found';
57         }
58         else
59         {
60                 // Location to look up
61                 $fLat = (float)$_GET['lat'];
62                 $fLon = (float)$_GET['lon'];
63                 $sPointSQL = "ST_SetSRID(ST_Point($fLon,$fLat),4326)";
64
65                 // Zoom to rank, this could probably be calculated but a lookup gives fine control
66                 $aZoomRank = array(
67                         0 => 2, // Continent / Sea
68                         1 => 2,
69                         2 => 2,
70                         3 => 4, // Country
71                         4 => 4,
72                         5 => 8, // State
73                         6 => 10, // Region
74                         7 => 10,
75                         8 => 12, // County
76                         9 => 12,
77                         10 => 17, // City
78                         11 => 17,
79                         12 => 18, // Town / Village
80                         13 => 18,
81                         14 => 22, // Suburb
82                         15 => 22,
83                         16 => 26, // Street, TODO: major street?
84                         17 => 26,
85                         18 => 30, // or >, Building
86                         19 => 30, // or >, Building
87                         );
88                 $iMaxRank = isset($aZoomRank[$_GET['zoom']])?$aZoomRank[$_GET['zoom']]:28;
89
90                 // Find the nearest point
91                 $fSearchDiam = 0.0001;
92                 $iPlaceID = null;
93                 $aArea = false;
94                 $fMaxAreaDistance = 1;
95                 while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
96                 {
97                         $fSearchDiam = $fSearchDiam * 2;
98
99                         // If we have to expand the search area by a large amount then we need a larger feature
100                         // then there is a limit to how small the feature should be
101                         if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4;
102                         if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8;
103                         if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10;
104                         if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12;
105                         if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17;
106                         if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18;
107                         if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22;
108                         if ($fSearchDiam > 0.001 && $iMaxRank > 26) $iMaxRank = 26;
109
110                         $sSQL = 'select place_id,parent_place_id,rank_search from placex';
111                         $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
112                         $sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank;
113                         $sSQL .= ' and (name is not null or housenumber is not null)';
114                         $sSQL .= ' and class not in (\'waterway\')';
115                         $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
116                         $sSQL .= ' OR ST_DWithin('.$sPointSQL.', ST_Centroid(geometry), '.$fSearchDiam.'))';
117                         $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
118 //var_dump($sSQL);
119                         $aPlace = $oDB->getRow($sSQL);
120                         $iPlaceID = $aPlace['place_id'];
121                         $iParentPlaceID = $aPlace['parent_place_id'];
122                         if (PEAR::IsError($iPlaceID))
123                         {
124                                 failInternalError("Could not determine closest place.", $sSQL, $iPlaceID); 
125                         }
126                 }
127
128                 // The point we found might be too small - use the address to find what it is a child of
129                 if ($iPlaceID && $iMaxRank < 28)
130                 {
131                         if ($aPlace['rank_search'] > 28 && $iParentPlaceID) {
132                                 $iPlaceID = $iParentPlaceID;
133                         }
134                         $sSQL = "select address_place_id from place_addressline where place_id = $iPlaceID order by abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc limit 1";
135                         $iPlaceID = $oDB->getOne($sSQL);
136                         if (PEAR::IsError($iPlaceID))
137                         {
138                                 failInternalError("Could not get parent for place.", $sSQL, $iPlaceID); 
139                         }
140                         if (!$iPlaceID)
141                         {
142                                 $iPlaceID = $aPlace['place_id'];
143                         }
144                 }
145         }
146
147         if ($iPlaceID)
148         {
149                 $sSQL = "select placex.*,";
150                 $sSQL .= " get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
151                 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
152                 $sSQL .= " get_name_by_language(name, ARRAY['ref']) as ref,";
153                 $sSQL .= " st_y(st_centroid(geometry)) as lat, st_x(st_centroid(geometry)) as lon";
154                 $sSQL .= " from placex where place_id = $iPlaceID ";
155 //var_dump($sSQL);
156                 $aPlace = $oDB->getRow($sSQL);
157
158                 if ($bShowAddressDetails)
159                 {
160                         $aAddress = getAddressDetails($oDB, $sLanguagePrefArraySQL, $iPlaceID, $aPlace['country_code']);
161                 }
162                 $aClassType = getClassTypes();
163                 $sAddressType = '';
164                 if (isset($aClassType[$aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level']]))
165                         $sAddressType = $aClassType[$aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level']]['simplelabel'];
166                 elseif (isset($aClassType[$aPlace['class'].':'.$aPlace['type']]))
167                         $sAddressType = $aClassType[$aPlace['class'].':'.$aPlace['type']]['simplelabel'];
168                 else $sAddressType = $aPlace['class'];
169                 $aPlace['addresstype'] = $sAddressType;
170
171         }
172         include(CONST_BasePath.'/lib/template/address-'.$sOutputFormat.'.php');