5 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
6 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
12 protected $aLangPrefOrder = array();
14 protected $bIncludeAddressDetails = false;
15 protected $bIncludeExtraTags = false;
16 protected $bIncludeNameDetails = false;
18 protected $bIncludePolygonAsPoints = false;
19 protected $bIncludePolygonAsText = false;
20 protected $bIncludePolygonAsGeoJSON = false;
21 protected $bIncludePolygonAsKML = false;
22 protected $bIncludePolygonAsSVG = false;
23 protected $fPolygonSimplificationThreshold = 0.0;
25 protected $aExcludePlaceIDs = array();
26 protected $bDeDupe = true;
27 protected $bReverseInPlan = false;
29 protected $iLimit = 20;
30 protected $iFinalLimit = 10;
31 protected $iOffset = 0;
32 protected $bFallback = false;
34 protected $aCountryCodes = false;
35 protected $aNearPoint = false;
37 protected $bBoundedSearch = false;
38 protected $aViewBox = false;
39 protected $sViewboxCentreSQL = false;
40 protected $sViewboxSmallSQL = false;
41 protected $sViewboxLargeSQL = false;
43 protected $iMaxRank = 20;
44 protected $iMinAddressRank = 0;
45 protected $iMaxAddressRank = 30;
46 protected $aAddressRankList = array();
47 protected $exactMatchCache = array();
49 protected $sAllowedTypesSQLList = false;
51 protected $sQuery = false;
52 protected $aStructuredQuery = false;
55 public function __construct(&$oDB)
60 public function setReverseInPlan($bReverse)
62 $this->bReverseInPlan = $bReverse;
65 public function setLanguagePreference($aLangPref)
67 $this->aLangPrefOrder = $aLangPref;
70 public function getIncludeAddressDetails()
72 return $this->bIncludeAddressDetails;
75 public function getIncludeExtraTags()
77 return $this->bIncludeExtraTags;
80 public function getIncludeNameDetails()
82 return $this->bIncludeNameDetails;
85 public function setIncludePolygonAsPoints($b = true)
87 $this->bIncludePolygonAsPoints = $b;
90 public function setIncludePolygonAsText($b = true)
92 $this->bIncludePolygonAsText = $b;
95 public function setIncludePolygonAsGeoJSON($b = true)
97 $this->bIncludePolygonAsGeoJSON = $b;
100 public function setIncludePolygonAsKML($b = true)
102 $this->bIncludePolygonAsKML = $b;
105 public function setIncludePolygonAsSVG($b = true)
107 $this->bIncludePolygonAsSVG = $b;
110 public function setPolygonSimplificationThreshold($f)
112 $this->fPolygonSimplificationThreshold = $f;
115 public function setLimit($iLimit = 10)
117 if ($iLimit > 50) $iLimit = 50;
118 if ($iLimit < 1) $iLimit = 1;
120 $this->iFinalLimit = $iLimit;
121 $this->iLimit = $iLimit + min($iLimit, 10);
124 public function getExcludedPlaceIDs()
126 return $this->aExcludePlaceIDs;
129 public function getViewBoxString()
131 if (!$this->aViewBox) return null;
132 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
135 public function setFeatureType($sFeatureType)
137 switch ($sFeatureType) {
139 $this->setRankRange(4, 4);
142 $this->setRankRange(8, 8);
145 $this->setRankRange(14, 16);
148 $this->setRankRange(8, 20);
153 public function setRankRange($iMin, $iMax)
155 $this->iMinAddressRank = $iMin;
156 $this->iMaxAddressRank = $iMax;
159 public function setRoute($aRoutePoints, $fRouteWidth)
161 $this->aViewBox = false;
163 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
165 foreach ($aRoutePoints as $aPoint) {
166 $fPoint = (float)$aPoint;
167 $this->sViewboxCentreSQL .= $sSep.$fPoint;
168 $sSep = ($sSep == ' ') ? ',' : ' ';
170 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
172 $this->sViewboxSmallSQL = 'st_buffer('.$this->sViewboxCentreSQL;
173 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
175 $this->sViewboxLargeSQL = 'st_buffer('.$this->sViewboxCentreSQL;
176 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
179 public function setViewbox($aViewbox)
181 $this->aViewBox = array_map('floatval', $aViewbox);
183 if ($this->aViewBox[0] < -180
184 || $this->aViewBox[2] > 180
185 || $this->aViewBox[0] >= $this->aViewBox[2]
186 || $this->aViewBox[1] < -90
187 || $this->aViewBox[3] > 90
188 || $this->aViewBox[1] >= $this->aViewBox[3]
190 userError("Bad parameter 'viewbox'. Out of range".$this->aViewBox[0]."|".$this->aViewBox[1]."|".$this->aViewBox[2]."|".$this->aViewBox[3]);
193 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
194 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
195 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
196 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
197 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
198 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
200 $this->sViewboxCentreSQL = false;
201 $this->sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".$this->aViewBox[0].",".$this->aViewBox[1]."),ST_Point(".$this->aViewBox[2].",".$this->aViewBox[3].")),4326)";
202 $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".$aBigViewBox[0].",".$aBigViewBox[1]."),ST_Point(".$aBigViewBox[2].",".$aBigViewBox[3].")),4326)";
205 public function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
207 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
210 public function setQuery($sQueryString)
212 $this->sQuery = $sQueryString;
213 $this->aStructuredQuery = false;
216 public function getQueryString()
218 return $this->sQuery;
222 public function loadParamArray($oParams)
224 $this->bIncludeAddressDetails
225 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
226 $this->bIncludeExtraTags
227 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
228 $this->bIncludeNameDetails
229 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
231 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
232 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
234 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
235 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
237 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
239 // List of excluded Place IDs - used for more acurate pageing
240 $sExcluded = $oParams->getStringList('exclude_place_ids');
242 foreach ($sExcluded as $iExcludedPlaceID) {
243 $iExcludedPlaceID = (int)$iExcludedPlaceID;
244 if ($iExcludedPlaceID)
245 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
248 if (isset($aExcludePlaceIDs))
249 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
252 // Only certain ranks of feature
253 $sFeatureType = $oParams->getString('featureType');
254 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
255 if ($sFeatureType) $this->setFeatureType($sFeatureType);
258 $sCountries = $oParams->getStringList('countrycodes');
260 foreach ($sCountries as $sCountryCode) {
261 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
262 $aCountries[] = strtolower($sCountryCode);
265 if (isset($aCountries))
266 $this->aCountryCodes = $aCountries;
269 $aViewbox = $oParams->getStringList('viewboxlbrt');
271 if (count($aViewbox) != 4) {
272 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
274 $this->setViewbox($aViewbox);
276 $aViewbox = $oParams->getStringList('viewbox');
278 if (count($aViewbox) != 4) {
279 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
281 $this->setViewBox(array(
288 $aRoute = $oParams->getStringList('route');
289 $fRouteWidth = $oParams->getFloat('routewidth');
290 if ($aRoute && $fRouteWidth) {
291 $this->setRoute($aRoute, $fRouteWidth);
297 public function setQueryFromParams($oParams)
300 $sQuery = $oParams->getString('q');
302 $this->setStructuredQuery(
303 $oParams->getString('amenity'),
304 $oParams->getString('street'),
305 $oParams->getString('city'),
306 $oParams->getString('county'),
307 $oParams->getString('state'),
308 $oParams->getString('country'),
309 $oParams->getString('postalcode')
311 $this->setReverseInPlan(false);
313 $this->setQuery($sQuery);
317 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
319 $sValue = trim($sValue);
320 if (!$sValue) return false;
321 $this->aStructuredQuery[$sKey] = $sValue;
322 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
323 $this->iMinAddressRank = $iNewMinAddressRank;
324 $this->iMaxAddressRank = $iNewMaxAddressRank;
326 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
330 public function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
332 $this->sQuery = false;
335 $this->iMinAddressRank = 0;
336 $this->iMaxAddressRank = 30;
337 $this->aAddressRankList = array();
339 $this->aStructuredQuery = array();
340 $this->sAllowedTypesSQLList = '';
342 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
343 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
344 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
345 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
346 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
347 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
348 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
350 if (sizeof($this->aStructuredQuery) > 0) {
351 $this->sQuery = join(', ', $this->aStructuredQuery);
352 if ($this->iMaxAddressRank < 30) {
353 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
358 public function fallbackStructuredQuery()
360 if (!$this->aStructuredQuery) return false;
362 $aParams = $this->aStructuredQuery;
364 if (sizeof($aParams) == 1) return false;
366 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
368 foreach ($aOrderToFallback as $sType) {
369 if (isset($aParams[$sType])) {
370 unset($aParams[$sType]);
371 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
379 public function getDetails($aPlaceIDs)
381 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
382 if (sizeof($aPlaceIDs) == 0) return array();
384 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
386 // Get the details for display (is this a redundant extra step?)
387 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
389 $sImportanceSQL = '';
390 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
391 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
393 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id, calculated_country_code as country_code,";
394 $sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
395 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
396 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
397 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text as extra,";
398 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text as names,";
399 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
400 $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
401 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
402 $sSQL .= "(extratags->'place') as extra_place ";
403 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
404 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
405 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
406 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
408 if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
409 $sSQL .= "and linked_place_id is null ";
410 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
411 if (!$this->bDeDupe) $sSQL .= ",place_id";
412 $sSQL .= ",langaddress ";
413 $sSQL .= ",placename ";
415 if ($this->bIncludeExtraTags) $sSQL .= ",extratags";
416 if ($this->bIncludeNameDetails) $sSQL .= ",name";
417 $sSQL .= ",extratags->'place' ";
419 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
420 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
421 // with start- and endnumber, the common osm housenumbers are usually saved as points
424 $length = count($aPlaceIDs);
425 foreach ($aPlaceIDs as $placeID => $housenumber) {
427 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
428 if ($i<$length) $sHousenumbers .= ", ";
430 if (CONST_Use_US_Tiger_Data) {
431 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
433 $sSQL .= " select 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code";
434 $sSQL .= ", get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress ";
435 $sSQL .= ", null as placename";
436 $sSQL .= ", null as ref";
437 if ($this->bIncludeExtraTags) $sSQL .= ", null as extra";
438 if ($this->bIncludeNameDetails) $sSQL .= ", null as names";
439 $sSQL .= ", avg(st_x(centroid)) as lon, avg(st_y(centroid)) as lat,";
440 $sSQL .= $sImportanceSQL."-1.15 as importance ";
441 $sSQL .= ", (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance ";
442 $sSQL .= ", null as extra_place ";
443 $sSQL .= " from (select place_id";
444 // interpolate the Tiger housenumbers here
445 $sSQL .= ", ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) as centroid, parent_place_id, housenumber_for_place";
446 $sSQL .= " from (location_property_tiger ";
447 $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
448 $sSQL .= " where housenumber_for_place>=0 and 30 between $this->iMinAddressRank and $this->iMaxAddressRank) as blub"; //postgres wants an alias here
449 $sSQL .= " group by place_id, housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
450 if (!$this->bDeDupe) $sSQL .= ", place_id ";
453 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
455 $sSQL .= "select 'W' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, calculated_country_code as country_code, ";
456 $sSQL .= "get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress, ";
457 $sSQL .= "null as placename, ";
458 $sSQL .= "null as ref, ";
459 if ($this->bIncludeExtraTags) $sSQL .= "null as extra, ";
460 if ($this->bIncludeNameDetails) $sSQL .= "null as names, ";
461 $sSQL .= " avg(st_x(centroid)) as lon, avg(st_y(centroid)) as lat,";
462 $sSQL .= $sImportanceSQL."-0.1 as importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
463 $sSQL .= " (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p";
464 $sSQL .= " where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance,";
465 $sSQL .= " null as extra_place ";
466 $sSQL .= " from (select place_id, calculated_country_code ";
467 // interpolate the housenumbers here
468 $sSQL .= ", CASE WHEN startnumber != endnumber THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
469 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) END as centroid";
470 $sSQL .= ", parent_place_id, housenumber_for_place ";
471 $sSQL .= " from (location_property_osmline ";
472 $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
473 $sSQL .= " where housenumber_for_place>=0 and 30 between $this->iMinAddressRank and $this->iMaxAddressRank) as blub"; //postgres wants an alias here
474 $sSQL .= " group by place_id, housenumber_for_place, calculated_country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
475 if (!$this->bDeDupe) $sSQL .= ", place_id ";
477 if (CONST_Use_Aux_Location_data) {
479 $sSQL .= "select 'L' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 0 as rank_search, 0 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code, ";
480 $sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress, ";
481 $sSQL .= "null as placename, ";
482 $sSQL .= "null as ref, ";
483 if ($this->bIncludeExtraTags) $sSQL .= "null as extra, ";
484 if ($this->bIncludeNameDetails) $sSQL .= "null as names, ";
485 $sSQL .= "avg(ST_X(centroid)) as lon, avg(ST_Y(centroid)) as lat, ";
486 $sSQL .= $sImportanceSQL."-1.10 as importance, ";
487 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
488 $sSQL .= "null as extra_place ";
489 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
490 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
491 $sSQL .= "group by place_id";
492 if (!$this->bDeDupe) $sSQL .= ", place_id";
493 $sSQL .= ", get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
497 $sSQL .= " order by importance desc";
502 $aSearchResults = chksql(
503 $this->oDB->getAll($sSQL),
504 "Could not get details for place."
507 return $aSearchResults;
510 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
513 Calculate all searches using aValidTokens i.e.
514 'Wodsworth Road, Sheffield' =>
518 0 1 (wodsworth)(road)
521 Score how good the search is so they can be ordered
523 foreach ($aPhrases as $iPhrase => $sPhrase) {
524 $aNewPhraseSearches = array();
525 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
526 else $sPhraseType = '';
528 foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
529 // Too many permutations - too expensive
530 if ($iWordSet > 120) break;
532 $aWordsetSearches = $aSearches;
534 // Add all words from this wordset
535 foreach ($aWordset as $iToken => $sToken) {
536 //echo "<br><b>$sToken</b>";
537 $aNewWordsetSearches = array();
539 foreach ($aWordsetSearches as $aCurrentSearch) {
541 //var_dump($aCurrentSearch);
544 // If the token is valid
545 if (isset($aValidTokens[' '.$sToken])) {
546 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
547 $aSearch = $aCurrentSearch;
548 $aSearch['iSearchRank']++;
549 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
550 if ($aSearch['sCountryCode'] === false) {
551 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
552 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
553 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
554 $aSearch['iSearchRank'] += 5;
556 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
558 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
559 if ($aSearch['fLat'] === '') {
560 $aSearch['fLat'] = $aSearchTerm['lat'];
561 $aSearch['fLon'] = $aSearchTerm['lon'];
562 $aSearch['fRadius'] = $aSearchTerm['radius'];
563 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
565 } elseif ($sPhraseType == 'postalcode') {
566 // We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
567 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
568 // If we already have a name try putting the postcode first
569 if (sizeof($aSearch['aName'])) {
570 $aNewSearch = $aSearch;
571 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
572 $aNewSearch['aName'] = array();
573 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
574 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
577 if (sizeof($aSearch['aName'])) {
578 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
579 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
581 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
582 $aSearch['iSearchRank'] += 1000; // skip;
585 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
586 //$aSearch['iNamePhrase'] = $iPhrase;
588 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
590 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
591 if ($aSearch['sHouseNumber'] === '') {
592 $aSearch['sHouseNumber'] = $sToken;
593 // sanity check: if the housenumber is not mainly made
594 // up of numbers, add a penalty
595 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
596 // also housenumbers should appear in the first or second phrase
597 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
598 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
600 // Fall back to not searching for this item (better than nothing)
601 $aSearch = $aCurrentSearch;
602 $aSearch['iSearchRank'] += 1;
603 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
606 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
607 if ($aSearch['sClass'] === '') {
608 $aSearch['sOperator'] = $aSearchTerm['operator'];
609 $aSearch['sClass'] = $aSearchTerm['class'];
610 $aSearch['sType'] = $aSearchTerm['type'];
611 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
612 else $aSearch['sOperator'] = 'near'; // near = in for the moment
613 if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
615 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
617 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
618 if (sizeof($aSearch['aName'])) {
619 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
620 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
622 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
623 $aSearch['iSearchRank'] += 1000; // skip;
626 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
627 //$aSearch['iNamePhrase'] = $iPhrase;
629 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
633 // Look for partial matches.
634 // Note that there is no point in adding country terms here
635 // because country are omitted in the address.
636 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
637 // Allow searching for a word - but at extra cost
638 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
639 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
640 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
641 $aSearch = $aCurrentSearch;
642 $aSearch['iSearchRank'] += 1;
643 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
644 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
645 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
646 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
647 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
648 $aSearch['iSearchRank'] += 1;
649 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
650 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
651 if (empty($aSearchTermToken['country_code'])
652 && empty($aSearchTermToken['lat'])
653 && empty($aSearchTermToken['class'])
655 $aSearch = $aCurrentSearch;
656 $aSearch['iSearchRank'] += 1;
657 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
658 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
662 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
663 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
664 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
668 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
669 $aSearch = $aCurrentSearch;
670 $aSearch['iSearchRank'] += 1;
671 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
672 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
673 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
674 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
676 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
678 $aSearch['iNamePhrase'] = $iPhrase;
679 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
684 // Allow skipping a word - but at EXTREAM cost
685 //$aSearch = $aCurrentSearch;
686 //$aSearch['iSearchRank']+=100;
687 //$aNewWordsetSearches[] = $aSearch;
691 usort($aNewWordsetSearches, 'bySearchRank');
692 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
694 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
696 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
697 usort($aNewPhraseSearches, 'bySearchRank');
699 $aSearchHash = array();
700 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
701 $sHash = serialize($aSearch);
702 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
703 else $aSearchHash[$sHash] = 1;
706 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
709 // Re-group the searches by their score, junk anything over 20 as just not worth trying
710 $aGroupedSearches = array();
711 foreach ($aNewPhraseSearches as $aSearch) {
712 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
713 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
714 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
717 ksort($aGroupedSearches);
720 $aSearches = array();
721 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
722 $iSearchCount += sizeof($aNewSearches);
723 $aSearches = array_merge($aSearches, $aNewSearches);
724 if ($iSearchCount > 50) break;
727 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
729 return $aGroupedSearches;
732 /* Perform the actual query lookup.
734 Returns an ordered list of results, each with the following fields:
735 osm_type: type of corresponding OSM object
739 P - postcode (internally computed)
740 osm_id: id of corresponding OSM object
741 class: general object class (corresponds to tag key of primary OSM tag)
742 type: subclass of object (corresponds to tag value of primary OSM tag)
743 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
744 rank_search: rank in search hierarchy
745 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
746 rank_address: rank in address hierarchy (determines orer in address)
747 place_id: internal key (may differ between different instances)
748 country_code: ISO country code
749 langaddress: localized full address
750 placename: localized name of object
751 ref: content of ref tag (if available)
754 importance: importance of place based on Wikipedia link count
755 addressimportance: cumulated importance of address elements
756 extra_place: type of place (for admin boundaries, if there is a place tag)
757 aBoundingBox: bounding Box
758 label: short description of the object class/type (English only)
759 name: full name (currently the same as langaddress)
760 foundorder: secondary ordering for places with same importance
764 public function lookup()
766 if (!$this->sQuery && !$this->aStructuredQuery) return false;
768 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
769 $sCountryCodesSQL = false;
770 if ($this->aCountryCodes) {
771 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
774 $sQuery = $this->sQuery;
775 if (!preg_match('//u', $sQuery)) {
776 userError("Query string is not UTF-8 encoded.");
779 // Conflicts between US state abreviations and various words for 'the' in different languages
780 if (isset($this->aLangPrefOrder['name:en'])) {
781 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
782 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
783 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
786 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
787 if ($this->sViewboxCentreSQL) {
788 // For complex viewboxes (routes) precompute the bounding geometry
790 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
791 "Could not get small viewbox"
793 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
796 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
797 "Could not get large viewbox"
799 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
802 // Do we have anything that looks like a lat/lon pair?
803 if ($aLooksLike = looksLikeLatLonPair($sQuery)) {
804 $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
805 $sQuery = $aLooksLike['query'];
808 $aSearchResults = array();
809 if ($sQuery || $this->aStructuredQuery) {
810 // Start with a blank search
815 'sCountryCode' => false,
817 'aAddress' => array(),
818 'aFullNameAddress' => array(),
819 'aNameNonSearch' => array(),
820 'aAddressNonSearch' => array(),
822 'aFeatureName' => array(),
825 'sHouseNumber' => '',
832 // Do we have a radius search?
833 $sNearPointSQL = false;
834 if ($this->aNearPoint) {
835 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
836 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
837 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
838 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
841 // Any 'special' terms in the search?
842 $bSpecialTerms = false;
843 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
844 $aSpecialTerms = array();
845 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
846 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
847 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
850 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
851 $aSpecialTerms = array();
852 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
853 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
854 unset($this->aStructuredQuery['amenity']);
857 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
858 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
859 $sToken = chksql($this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string"));
860 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
861 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
862 if (CONST_Debug) var_Dump($sSQL);
863 $aSearchWords = chksql($this->oDB->getAll($sSQL));
864 $aNewSearches = array();
865 foreach ($aSearches as $aSearch) {
866 foreach ($aSearchWords as $aSearchTerm) {
867 $aNewSearch = $aSearch;
868 if ($aSearchTerm['country_code']) {
869 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
870 $aNewSearches[] = $aNewSearch;
871 $bSpecialTerms = true;
873 if ($aSearchTerm['class']) {
874 $aNewSearch['sClass'] = $aSearchTerm['class'];
875 $aNewSearch['sType'] = $aSearchTerm['type'];
876 $aNewSearches[] = $aNewSearch;
877 $bSpecialTerms = true;
881 $aSearches = $aNewSearches;
884 // Split query into phrases
885 // Commas are used to reduce the search space by indicating where phrases split
886 if ($this->aStructuredQuery) {
887 $aPhrases = $this->aStructuredQuery;
888 $bStructuredPhrases = true;
890 $aPhrases = explode(',', $sQuery);
891 $bStructuredPhrases = false;
894 // Convert each phrase to standard form
895 // Create a list of standard words
896 // Get all 'sets' of words
897 // Generate a complete list of all
899 foreach ($aPhrases as $iPhrase => $sPhrase) {
901 $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string"),
902 "Cannot normalize query string (is it a UTF-8 string?)"
904 if (trim($aPhrase['string'])) {
905 $aPhrases[$iPhrase] = $aPhrase;
906 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
907 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
908 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
910 unset($aPhrases[$iPhrase]);
914 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
915 $aPhraseTypes = array_keys($aPhrases);
916 $aPhrases = array_values($aPhrases);
918 if (sizeof($aTokens)) {
919 // Check which tokens we have, get the ID numbers
920 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
921 $sSQL .= ' from word where word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
923 if (CONST_Debug) var_Dump($sSQL);
925 $aValidTokens = array();
926 if (sizeof($aTokens)) {
927 $aDatabaseWords = chksql(
928 $this->oDB->getAll($sSQL),
929 "Could not get word tokens."
932 $aDatabaseWords = array();
934 $aPossibleMainWordIDs = array();
935 $aWordFrequencyScores = array();
936 foreach ($aDatabaseWords as $aToken) {
937 // Very special case - require 2 letter country param to match the country code found
938 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
939 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
944 if (isset($aValidTokens[$aToken['word_token']])) {
945 $aValidTokens[$aToken['word_token']][] = $aToken;
947 $aValidTokens[$aToken['word_token']] = array($aToken);
949 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
950 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
952 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
954 // Try and calculate GB postcodes we might be missing
955 foreach ($aTokens as $sToken) {
956 // Source of gb postcodes is now definitive - always use
957 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
958 if (substr($aData[1], -2, 1) != ' ') {
959 $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
960 $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
962 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
963 if ($aGBPostcodeLocation) {
964 $aValidTokens[$sToken] = $aGBPostcodeLocation;
966 } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
967 // US ZIP+4 codes - if there is no token,
968 // merge in the 5-digit ZIP code
969 if (isset($aValidTokens[$aData[1]])) {
970 foreach ($aValidTokens[$aData[1]] as $aToken) {
971 if (!$aToken['class']) {
972 if (isset($aValidTokens[$sToken])) {
973 $aValidTokens[$sToken][] = $aToken;
975 $aValidTokens[$sToken] = array($aToken);
983 foreach ($aTokens as $sToken) {
984 // Unknown single word token with a number - assume it is a house number
985 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
986 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
990 // Any words that have failed completely?
993 // Start the search process
994 // array with: placeid => -1 | tiger-housenumber
995 $aResultPlaceIDs = array();
997 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
999 if ($this->bReverseInPlan) {
1000 // Reverse phrase array and also reverse the order of the wordsets in
1001 // the first and final phrase. Don't bother about phrases in the middle
1002 // because order in the address doesn't matter.
1003 $aPhrases = array_reverse($aPhrases);
1004 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1005 if (sizeof($aPhrases) > 1) {
1006 $aFinalPhrase = end($aPhrases);
1007 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1009 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1011 foreach ($aGroupedSearches as $aSearches) {
1012 foreach ($aSearches as $aSearch) {
1013 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1014 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1015 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1020 $aGroupedSearches = $aReverseGroupedSearches;
1021 ksort($aGroupedSearches);
1024 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1025 $aGroupedSearches = array();
1026 foreach ($aSearches as $aSearch) {
1027 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1028 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1029 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1032 ksort($aGroupedSearches);
1035 if (CONST_Debug) var_Dump($aGroupedSearches);
1036 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1037 $aCopyGroupedSearches = $aGroupedSearches;
1038 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1039 foreach ($aSearches as $iSearch => $aSearch) {
1040 $aReductionsList = array($aSearch['aAddress']);
1041 $iSearchRank = $aSearch['iSearchRank'];
1042 while (sizeof($aReductionsList) > 0) {
1044 if ($iSearchRank > iMaxRank) break 3;
1045 $aNewReductionsList = array();
1046 foreach ($aReductionsList as $aReductionsWordList) {
1047 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1048 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1049 $aReverseSearch = $aSearch;
1050 $aSearch['aAddress'] = $aReductionsWordListResult;
1051 $aSearch['iSearchRank'] = $iSearchRank;
1052 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1053 if (sizeof($aReductionsWordListResult) > 0) {
1054 $aNewReductionsList[] = $aReductionsWordListResult;
1058 $aReductionsList = $aNewReductionsList;
1062 ksort($aGroupedSearches);
1065 // Filter out duplicate searches
1066 $aSearchHash = array();
1067 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1068 foreach ($aSearches as $iSearch => $aSearch) {
1069 $sHash = serialize($aSearch);
1070 if (isset($aSearchHash[$sHash])) {
1071 unset($aGroupedSearches[$iGroup][$iSearch]);
1072 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1074 $aSearchHash[$sHash] = 1;
1079 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1083 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1085 foreach ($aSearches as $aSearch) {
1087 $searchedHousenumber = -1;
1089 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1090 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1092 // No location term?
1093 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon']) {
1094 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1095 // Just looking for a country by code - look it up
1096 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1097 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1098 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1099 if ($bBoundingBoxSearch)
1100 $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
1101 $sSQL .= " order by st_area(geometry) desc limit 1";
1102 if (CONST_Debug) var_dump($sSQL);
1103 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1105 $aPlaceIDs = array();
1108 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1109 if (!$aSearch['sClass']) continue;
1111 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1112 if (chksql($this->oDB->getOne($sSQL))) {
1113 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1114 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1115 $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1116 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1117 if (sizeof($this->aExcludePlaceIDs)) {
1118 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1120 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1121 $sSQL .= " limit $this->iLimit";
1122 if (CONST_Debug) var_dump($sSQL);
1123 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1125 // If excluded place IDs are given, it is fair to assume that
1126 // there have been results in the small box, so no further
1127 // expansion in that case.
1128 // Also don't expand if bounded results were requested.
1129 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1130 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1131 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1132 $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1133 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1134 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1135 $sSQL .= " limit $this->iLimit";
1136 if (CONST_Debug) var_dump($sSQL);
1137 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1140 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1141 $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1142 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1143 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, centroid) asc";
1144 $sSQL .= " limit $this->iLimit";
1145 if (CONST_Debug) var_dump($sSQL);
1146 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1149 } elseif ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1150 // If a coordinate is given, the search must either
1151 // be for a name or a special search. Ignore everythin else.
1152 $aPlaceIDs = array();
1154 $aPlaceIDs = array();
1156 // First we need a position, either aName or fLat or both
1160 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1161 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1163 $aOrder[0] = " (exists(select place_id from placex where parent_place_id = search_name.place_id";
1164 $aOrder[0] .= " and transliteration(housenumber) ~* E'".$sHouseNumberRegex."' limit 1) ";
1165 // also housenumbers from interpolation lines table are needed
1166 $aOrder[0] .= " or exists(select place_id from location_property_osmline where parent_place_id = search_name.place_id";
1167 $aOrder[0] .= " and ".intval($aSearch['sHouseNumber']).">=startnumber and ".intval($aSearch['sHouseNumber'])."<=endnumber limit 1))";
1168 $aOrder[0] .= " desc";
1171 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1172 // they might be right - but they are just too darned expensive to run
1173 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1174 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1175 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1176 // For infrequent name terms disable index usage for address
1177 if (CONST_Search_NameOnlySearchFrequencyThreshold
1178 && sizeof($aSearch['aName']) == 1
1179 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1181 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1183 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1184 if (sizeof($aSearch['aAddressNonSearch'])) {
1185 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1189 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1190 if ($aSearch['sHouseNumber']) {
1191 $aTerms[] = "address_rank between 16 and 27";
1193 if ($this->iMinAddressRank > 0) {
1194 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1196 if ($this->iMaxAddressRank < 30) {
1197 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1200 if ($aSearch['fLon'] && $aSearch['fLat']) {
1201 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1202 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1204 if (sizeof($this->aExcludePlaceIDs)) {
1205 $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1207 if ($sCountryCodesSQL) {
1208 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1211 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1212 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1214 if ($aSearch['sHouseNumber']) {
1215 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1217 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1219 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1220 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1222 $aOrder[] = "$sImportanceSQL DESC";
1223 if (sizeof($aSearch['aFullNameAddress'])) {
1224 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1225 $aOrder[] = 'exactmatch DESC';
1227 $sExactMatchSQL = '0::int as exactmatch';
1230 if (sizeof($aTerms)) {
1231 $sSQL = "select place_id, ";
1232 $sSQL .= $sExactMatchSQL;
1233 $sSQL .= " from search_name";
1234 $sSQL .= " where ".join(' and ', $aTerms);
1235 $sSQL .= " order by ".join(', ', $aOrder);
1236 if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1237 $sSQL .= " limit 20";
1238 } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1239 $sSQL .= " limit 1";
1241 $sSQL .= " limit ".$this->iLimit;
1244 if (CONST_Debug) var_dump($sSQL);
1245 $aViewBoxPlaceIDs = chksql(
1246 $this->oDB->getAll($sSQL),
1247 "Could not get places for search terms."
1249 //var_dump($aViewBoxPlaceIDs);
1250 // Did we have an viewbox matches?
1251 $aPlaceIDs = array();
1252 $bViewBoxMatch = false;
1253 foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1254 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1255 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1256 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1257 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1258 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1259 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1262 //var_Dump($aPlaceIDs);
1265 //now search for housenumber, if housenumber provided
1266 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1267 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1268 $aRoadPlaceIDs = $aPlaceIDs;
1269 $sPlaceIDs = join(',', $aPlaceIDs);
1271 // Now they are indexed, look for a house attached to a street we found
1272 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1273 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1274 if (sizeof($this->aExcludePlaceIDs)) {
1275 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1277 $sSQL .= " limit $this->iLimit";
1278 if (CONST_Debug) var_dump($sSQL);
1279 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1281 // if nothing found, search in the interpolation line table
1282 if (!sizeof($aPlaceIDs)) {
1283 // do we need to use transliteration and the regex for housenumbers???
1284 //new query for lines, not housenumbers anymore
1285 if ($searchedHousenumber%2 == 0) {
1286 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1287 $sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1289 //look for housenumber in streets with interpolationtype odd or all
1290 $sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1293 if (sizeof($this->aExcludePlaceIDs)) {
1294 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1296 //$sSQL .= " limit $this->iLimit";
1297 if (CONST_Debug) var_dump($sSQL);
1299 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1302 // If nothing found try the aux fallback table
1303 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1304 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1305 if (sizeof($this->aExcludePlaceIDs)) {
1306 $sSQL .= " and parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1308 //$sSQL .= " limit $this->iLimit";
1309 if (CONST_Debug) var_dump($sSQL);
1310 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1313 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1314 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1315 //new query for lines, not housenumbers anymore
1316 if ($searchedHousenumber%2 == 0) {
1317 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1318 $sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1320 //look for housenumber in streets with interpolationtype odd or all
1321 $sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1324 if (sizeof($this->aExcludePlaceIDs)) {
1325 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1327 //$sSQL .= " limit $this->iLimit";
1328 if (CONST_Debug) var_dump($sSQL);
1330 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1333 // Fallback to the road (if no housenumber was found)
1334 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1335 $aPlaceIDs = $aRoadPlaceIDs;
1336 //set to -1, if no housenumbers were found
1337 $searchedHousenumber = -1;
1339 //else: housenumber was found, remains saved in searchedHousenumber
1343 if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1344 $sPlaceIDs = join(',', $aPlaceIDs);
1345 $aClassPlaceIDs = array();
1347 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1348 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1349 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1350 $sSQL .= " and linked_place_id is null";
1351 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1352 $sSQL .= " order by rank_search asc limit $this->iLimit";
1353 if (CONST_Debug) var_dump($sSQL);
1354 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1357 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1358 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1359 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1361 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1363 if (CONST_Debug) var_dump($sSQL);
1364 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1366 // For state / country level searches the normal radius search doesn't work very well
1367 $sPlaceGeom = false;
1368 if ($this->iMaxRank < 9 && $bCacheTable) {
1369 // Try and get a polygon to search in instead
1370 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
1371 if (CONST_Debug) var_dump($sSQL);
1372 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1378 $this->iMaxRank += 5;
1379 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1380 if (CONST_Debug) var_dump($sSQL);
1381 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1382 $sPlaceIDs = join(',', $aPlaceIDs);
1385 if ($sPlaceIDs || $sPlaceGeom) {
1388 // More efficient - can make the range bigger
1392 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1393 elseif ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1394 elseif ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1396 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1397 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1399 $sSQL .= ",placex as f where ";
1400 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1404 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1406 if (sizeof($this->aExcludePlaceIDs)) {
1407 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1409 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1410 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1411 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1412 $sSQL .= " limit $this->iLimit";
1413 if (CONST_Debug) var_dump($sSQL);
1414 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1416 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1419 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1420 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1422 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1423 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1424 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1425 if (sizeof($this->aExcludePlaceIDs)) {
1426 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1428 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1429 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1430 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1431 $sSQL .= " limit $this->iLimit";
1432 if (CONST_Debug) var_dump($sSQL);
1433 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1437 $aPlaceIDs = $aClassPlaceIDs;
1442 echo "<br><b>Place IDs:</b> ";
1443 var_Dump($aPlaceIDs);
1446 foreach ($aPlaceIDs as $iPlaceID) {
1447 // array for placeID => -1 | Tiger housenumber
1448 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1450 if ($iQueryLoop > 20) break;
1453 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1454 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1455 // reduces the number of place ids, like a filter
1456 // rank_address is 30 for interpolated housenumbers
1457 $sSQL = "select place_id from placex where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1458 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1459 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1460 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1461 if (CONST_Use_US_Tiger_Data) {
1462 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1463 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1464 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1466 $sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1467 $sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1468 if (CONST_Debug) var_dump($sSQL);
1469 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1471 foreach ($aFilteredPlaceIDs as $placeID) {
1472 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1474 $aResultPlaceIDs = $tempIDs;
1478 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1479 if ($iGroupLoop > 4) break;
1480 if ($iQueryLoop > 30) break;
1483 // Did we find anything?
1484 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1485 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1488 // Just interpret as a reverse geocode
1489 $oReverse = new ReverseGeocode($this->oDB);
1490 $oReverse->setZoom(18);
1492 $aLookup = $oReverse->lookup(
1493 (float)$this->aNearPoint[0],
1494 (float)$this->aNearPoint[1],
1498 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1500 if ($aLookup['place_id']) {
1501 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1502 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1504 $aSearchResults = array();
1509 if (!sizeof($aSearchResults)) {
1510 if ($this->bFallback) {
1511 if ($this->fallbackStructuredQuery()) {
1512 return $this->lookup();
1519 $aClassType = getClassTypesWithImportance();
1520 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1521 foreach ($aRecheckWords as $i => $sWord) {
1522 if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1526 echo '<i>Recheck words:<\i>';
1527 var_dump($aRecheckWords);
1530 $oPlaceLookup = new PlaceLookup($this->oDB);
1531 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1532 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1533 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1534 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1535 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1536 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1538 foreach ($aSearchResults as $iResNum => $aResult) {
1540 $fDiameter = getResultDiameter($aResult);
1542 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1543 if ($aOutlineResult) {
1544 $aResult = array_merge($aResult, $aOutlineResult);
1547 if ($aResult['extra_place'] == 'city') {
1548 $aResult['class'] = 'place';
1549 $aResult['type'] = 'city';
1550 $aResult['rank_search'] = 16;
1553 // Is there an icon set for this type of result?
1554 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1555 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1557 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1560 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1561 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1563 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1564 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1565 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1567 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1569 // if tag '&addressdetails=1' is set in query
1570 if ($this->bIncludeAddressDetails) {
1571 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1572 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1573 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1574 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1578 if ($this->bIncludeExtraTags) {
1579 if ($aResult['extra']) {
1580 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1582 $aResult['sExtraTags'] = (object) array();
1586 if ($this->bIncludeNameDetails) {
1587 if ($aResult['names']) {
1588 $aResult['sNameDetails'] = json_decode($aResult['names']);
1590 $aResult['sNameDetails'] = (object) array();
1594 // Adjust importance for the number of exact string matches in the result
1595 $aResult['importance'] = max(0.001, $aResult['importance']);
1597 $sAddress = $aResult['langaddress'];
1598 foreach ($aRecheckWords as $i => $sWord) {
1599 if (stripos($sAddress, $sWord)!==false) {
1601 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1605 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1); // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
1607 $aResult['name'] = $aResult['langaddress'];
1608 // secondary ordering (for results with same importance (the smaller the better):
1609 // - approximate importance of address parts
1610 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1611 // - number of exact matches from the query
1612 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1613 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1614 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1615 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1617 // - importance of the class/type
1618 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1619 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1621 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1623 $aResult['foundorder'] += 0.01;
1625 if (CONST_Debug) var_dump($aResult);
1626 $aSearchResults[$iResNum] = $aResult;
1628 uasort($aSearchResults, 'byImportance');
1630 $aOSMIDDone = array();
1631 $aClassTypeNameDone = array();
1632 $aToFilter = $aSearchResults;
1633 $aSearchResults = array();
1636 foreach ($aToFilter as $iResNum => $aResult) {
1637 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1639 $fLat = $aResult['lat'];
1640 $fLon = $aResult['lon'];
1641 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1644 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1645 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1647 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1648 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1649 $aSearchResults[] = $aResult;
1652 // Absolute limit on number of results
1653 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1656 return $aSearchResults;