6 protected $aLangPrefOrder = array();
8 protected $bIncludeAddressDetails = false;
9 protected $bIncludeExtraTags = false;
10 protected $bIncludeNameDetails = false;
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;
19 protected $aExcludePlaceIDs = array();
20 protected $bDeDupe = true;
21 protected $bReverseInPlan = false;
23 protected $iLimit = 20;
24 protected $iFinalLimit = 10;
25 protected $iOffset = 0;
26 protected $bFallback = false;
28 protected $aCountryCodes = false;
29 protected $aNearPoint = false;
31 protected $bBoundedSearch = false;
32 protected $aViewBox = false;
33 protected $sViewboxSmallSQL = false;
34 protected $sViewboxLargeSQL = false;
35 protected $aRoutePoints = false;
37 protected $iMaxRank = 20;
38 protected $iMinAddressRank = 0;
39 protected $iMaxAddressRank = 30;
40 protected $aAddressRankList = array();
41 protected $exactMatchCache = array();
43 protected $sAllowedTypesSQLList = false;
45 protected $sQuery = false;
46 protected $aStructuredQuery = false;
48 function Geocode(&$oDB)
53 function setReverseInPlan($bReverse)
55 $this->bReverseInPlan = $bReverse;
58 function setLanguagePreference($aLangPref)
60 $this->aLangPrefOrder = $aLangPref;
63 function setIncludeAddressDetails($bAddressDetails = true)
65 $this->bIncludeAddressDetails = (bool)$bAddressDetails;
68 function getIncludeAddressDetails()
70 return $this->bIncludeAddressDetails;
73 function getIncludeExtraTags()
75 return $this->bIncludeExtraTags;
78 function getIncludeNameDetails()
80 return $this->bIncludeNameDetails;
83 function setIncludePolygonAsPoints($b = true)
85 $this->bIncludePolygonAsPoints = $b;
88 function getIncludePolygonAsPoints()
90 return $this->bIncludePolygonAsPoints;
93 function setIncludePolygonAsText($b = true)
95 $this->bIncludePolygonAsText = $b;
98 function getIncludePolygonAsText()
100 return $this->bIncludePolygonAsText;
103 function setIncludePolygonAsGeoJSON($b = true)
105 $this->bIncludePolygonAsGeoJSON = $b;
108 function setIncludePolygonAsKML($b = true)
110 $this->bIncludePolygonAsKML = $b;
113 function setIncludePolygonAsSVG($b = true)
115 $this->bIncludePolygonAsSVG = $b;
118 function setPolygonSimplificationThreshold($f)
120 $this->fPolygonSimplificationThreshold = $f;
123 function setDeDupe($bDeDupe = true)
125 $this->bDeDupe = (bool)$bDeDupe;
128 function setLimit($iLimit = 10)
130 if ($iLimit > 50) $iLimit = 50;
131 if ($iLimit < 1) $iLimit = 1;
133 $this->iFinalLimit = $iLimit;
134 $this->iLimit = $this->iFinalLimit + min($this->iFinalLimit, 10);
137 function setOffset($iOffset = 0)
139 $this->iOffset = $iOffset;
142 function setFallback($bFallback = true)
144 $this->bFallback = (bool)$bFallback;
147 function setExcludedPlaceIDs($a)
149 // TODO: force to int
150 $this->aExcludePlaceIDs = $a;
153 function getExcludedPlaceIDs()
155 return $this->aExcludePlaceIDs;
158 function setBounded($bBoundedSearch = true)
160 $this->bBoundedSearch = (bool)$bBoundedSearch;
163 function setViewBox($fLeft, $fBottom, $fRight, $fTop)
165 $this->aViewBox = array($fLeft, $fBottom, $fRight, $fTop);
168 function getViewBoxString()
170 if (!$this->aViewBox) return null;
171 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
174 function setRoute($aRoutePoints)
176 $this->aRoutePoints = $aRoutePoints;
179 function setFeatureType($sFeatureType)
181 switch($sFeatureType)
184 $this->setRankRange(4, 4);
187 $this->setRankRange(8, 8);
190 $this->setRankRange(14, 16);
193 $this->setRankRange(8, 20);
198 function setRankRange($iMin, $iMax)
200 $this->iMinAddressRank = (int)$iMin;
201 $this->iMaxAddressRank = (int)$iMax;
204 function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
206 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
209 function setCountryCodesList($aCountryCodes)
211 $this->aCountryCodes = $aCountryCodes;
214 function setQuery($sQueryString)
216 $this->sQuery = $sQueryString;
217 $this->aStructuredQuery = false;
220 function getQueryString()
222 return $this->sQuery;
226 function loadParamArray($aParams)
228 if (isset($aParams['addressdetails'])) $this->bIncludeAddressDetails = (bool)$aParams['addressdetails'];
229 if ((float) CONST_Postgresql_Version > 9.2)
231 if (isset($aParams['extratags'])) $this->bIncludeExtraTags = (bool)$aParams['extratags'];
232 if (isset($aParams['namedetails'])) $this->bIncludeNameDetails = (bool)$aParams['namedetails'];
234 if (isset($aParams['bounded'])) $this->bBoundedSearch = (bool)$aParams['bounded'];
235 if (isset($aParams['dedupe'])) $this->bDeDupe = (bool)$aParams['dedupe'];
237 if (isset($aParams['limit'])) $this->setLimit((int)$aParams['limit']);
238 if (isset($aParams['offset'])) $this->iOffset = (int)$aParams['offset'];
240 if (isset($aParams['fallback'])) $this->bFallback = (bool)$aParams['fallback'];
242 // List of excluded Place IDs - used for more acurate pageing
243 if (isset($aParams['exclude_place_ids']) && $aParams['exclude_place_ids'])
245 foreach(explode(',',$aParams['exclude_place_ids']) as $iExcludedPlaceID)
247 $iExcludedPlaceID = (int)$iExcludedPlaceID;
248 if ($iExcludedPlaceID)
249 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
252 if (isset($aExcludePlaceIDs))
253 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
256 // Only certain ranks of feature
257 if (isset($aParams['featureType'])) $this->setFeatureType($aParams['featureType']);
258 if (isset($aParams['featuretype'])) $this->setFeatureType($aParams['featuretype']);
261 if (isset($aParams['countrycodes']))
263 $aCountryCodes = array();
264 foreach(explode(',',$aParams['countrycodes']) as $sCountryCode)
266 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
268 $aCountryCodes[] = strtolower($sCountryCode);
271 $this->aCountryCodes = $aCountryCodes;
274 if (isset($aParams['viewboxlbrt']) && $aParams['viewboxlbrt'])
276 $aCoOrdinatesLBRT = explode(',',$aParams['viewboxlbrt']);
277 $this->setViewBox($aCoOrdinatesLBRT[0], $aCoOrdinatesLBRT[1], $aCoOrdinatesLBRT[2], $aCoOrdinatesLBRT[3]);
279 else if (isset($aParams['viewbox']) && $aParams['viewbox'])
281 $aCoOrdinatesLTRB = explode(',',$aParams['viewbox']);
282 $this->setViewBox($aCoOrdinatesLTRB[0], $aCoOrdinatesLTRB[3], $aCoOrdinatesLTRB[2], $aCoOrdinatesLTRB[1]);
285 if (isset($aParams['route']) && $aParams['route'] && isset($aParams['routewidth']) && $aParams['routewidth'])
287 $aPoints = explode(',',$aParams['route']);
288 if (sizeof($aPoints) % 2 != 0)
290 userError("Uneven number of points");
295 foreach($aPoints as $i => $fPoint)
299 $aRoute[] = array((float)$fPoint, $fPrevCoord);
303 $fPrevCoord = (float)$fPoint;
306 $this->aRoutePoints = $aRoute;
310 function setQueryFromParams($aParams)
313 $sQuery = (isset($aParams['q'])?trim($aParams['q']):'');
316 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
317 $this->setReverseInPlan(false);
321 $this->setQuery($sQuery);
325 function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
327 $sValue = trim($sValue);
328 if (!$sValue) return false;
329 $this->aStructuredQuery[$sKey] = $sValue;
330 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30)
332 $this->iMinAddressRank = $iNewMinAddressRank;
333 $this->iMaxAddressRank = $iNewMaxAddressRank;
335 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
339 function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
341 $this->sQuery = false;
344 $this->iMinAddressRank = 0;
345 $this->iMaxAddressRank = 30;
346 $this->aAddressRankList = array();
348 $this->aStructuredQuery = array();
349 $this->sAllowedTypesSQLList = '';
351 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
352 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
353 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
354 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
355 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
356 $this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11));
357 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
359 if (sizeof($this->aStructuredQuery) > 0)
361 $this->sQuery = join(', ', $this->aStructuredQuery);
362 if ($this->iMaxAddressRank < 30)
364 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
369 function fallbackStructuredQuery()
371 if (!$this->aStructuredQuery) return false;
373 $aParams = $this->aStructuredQuery;
375 if (sizeof($aParams) == 1) return false;
377 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
379 foreach($aOrderToFallback as $sType)
381 if (isset($aParams[$sType]))
383 unset($aParams[$sType]);
384 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
392 function getDetails($aPlaceIDs)
394 if (sizeof($aPlaceIDs) == 0) return array();
396 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
398 // Get the details for display (is this a redundant extra step?)
399 $sPlaceIDs = join(',',$aPlaceIDs);
401 $sImportanceSQL = '';
402 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
403 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
405 $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,";
406 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
407 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
408 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
409 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text as extra,";
410 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text as names,";
411 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
412 $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
413 $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, ";
414 $sSQL .= "(extratags->'place') as extra_place ";
415 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
416 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
417 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
418 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
420 if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
421 $sSQL .= "and linked_place_id is null ";
422 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
423 if (!$this->bDeDupe) $sSQL .= ",place_id";
424 $sSQL .= ",langaddress ";
425 $sSQL .= ",placename ";
427 if ($this->bIncludeExtraTags) $sSQL .= ",extratags";
428 if ($this->bIncludeNameDetails) $sSQL .= ",name";
429 $sSQL .= ",extratags->'place' ";
431 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
434 $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,";
435 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
436 $sSQL .= "null as placename,";
437 $sSQL .= "null as ref,";
438 if ($this->bIncludeExtraTags) $sSQL .= "null as extra,";
439 if ($this->bIncludeNameDetails) $sSQL .= "null as names,";
440 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
441 $sSQL .= $sImportanceSQL."-1.15 as importance, ";
442 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_tiger.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
443 $sSQL .= "null as extra_place ";
444 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
445 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
446 $sSQL .= "group by place_id";
447 if (!$this->bDeDupe) $sSQL .= ",place_id ";
449 $sSQL .= "select 'L' 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,";
450 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
451 $sSQL .= "null as placename,";
452 $sSQL .= "null as ref,";
453 if ($this->bIncludeExtraTags) $sSQL .= "null as extra,";
454 if ($this->bIncludeNameDetails) $sSQL .= "null as names,";
455 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
456 $sSQL .= $sImportanceSQL."-1.10 as importance, ";
457 $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, ";
458 $sSQL .= "null as extra_place ";
459 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
460 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
461 $sSQL .= "group by place_id";
462 if (!$this->bDeDupe) $sSQL .= ",place_id";
463 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
466 $sSQL .= " order by importance desc";
467 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
468 $aSearchResults = $this->oDB->getAll($sSQL);
470 if (PEAR::IsError($aSearchResults))
472 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
475 return $aSearchResults;
478 function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
481 Calculate all searches using aValidTokens i.e.
482 'Wodsworth Road, Sheffield' =>
486 0 1 (wodsworth)(road)
489 Score how good the search is so they can be ordered
491 foreach($aPhrases as $iPhrase => $sPhrase)
493 $aNewPhraseSearches = array();
494 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
495 else $sPhraseType = '';
497 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
499 // Too many permutations - too expensive
500 if ($iWordSet > 120) break;
502 $aWordsetSearches = $aSearches;
504 // Add all words from this wordset
505 foreach($aWordset as $iToken => $sToken)
507 //echo "<br><b>$sToken</b>";
508 $aNewWordsetSearches = array();
510 foreach($aWordsetSearches as $aCurrentSearch)
513 //var_dump($aCurrentSearch);
516 // If the token is valid
517 if (isset($aValidTokens[' '.$sToken]))
519 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
521 $aSearch = $aCurrentSearch;
522 $aSearch['iSearchRank']++;
523 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
525 if ($aSearch['sCountryCode'] === false)
527 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
528 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
529 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)))
531 $aSearch['iSearchRank'] += 5;
533 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
536 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
538 if ($aSearch['fLat'] === '')
540 $aSearch['fLat'] = $aSearchTerm['lat'];
541 $aSearch['fLon'] = $aSearchTerm['lon'];
542 $aSearch['fRadius'] = $aSearchTerm['radius'];
543 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
546 elseif ($sPhraseType == 'postalcode')
548 // 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
549 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
551 // If we already have a name try putting the postcode first
552 if (sizeof($aSearch['aName']))
554 $aNewSearch = $aSearch;
555 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
556 $aNewSearch['aName'] = array();
557 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
558 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
561 if (sizeof($aSearch['aName']))
563 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
565 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
569 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
570 $aSearch['iSearchRank'] += 1000; // skip;
575 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
576 //$aSearch['iNamePhrase'] = $iPhrase;
578 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
582 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
584 if ($aSearch['sHouseNumber'] === '')
586 $aSearch['sHouseNumber'] = $sToken;
587 // sanity check: if the housenumber is not mainly made
588 // up of numbers, add a penalty
589 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
590 // also housenumbers should appear in the first or second phrase
591 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
592 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
594 // Fall back to not searching for this item (better than nothing)
595 $aSearch = $aCurrentSearch;
596 $aSearch['iSearchRank'] += 1;
597 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
601 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
603 if ($aSearch['sClass'] === '')
605 $aSearch['sOperator'] = $aSearchTerm['operator'];
606 $aSearch['sClass'] = $aSearchTerm['class'];
607 $aSearch['sType'] = $aSearchTerm['type'];
608 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
609 else $aSearch['sOperator'] = 'near'; // near = in for the moment
610 if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
612 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
615 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
617 if (sizeof($aSearch['aName']))
619 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
621 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
625 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
626 $aSearch['iSearchRank'] += 1000; // skip;
631 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
632 //$aSearch['iNamePhrase'] = $iPhrase;
634 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
638 // Look for partial matches.
639 // Note that there is no point in adding country terms here
640 // because country are omitted in the address.
641 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country')
643 // Allow searching for a word - but at extra cost
644 foreach($aValidTokens[$sToken] as $aSearchTerm)
646 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
648 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false)
650 $aSearch = $aCurrentSearch;
651 $aSearch['iSearchRank'] += 1;
652 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
654 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
655 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
657 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
659 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
660 $aSearch['iSearchRank'] += 1;
661 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
662 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
664 if (empty($aSearchTermToken['country_code'])
665 && empty($aSearchTermToken['lat'])
666 && empty($aSearchTermToken['class']))
668 $aSearch = $aCurrentSearch;
669 $aSearch['iSearchRank'] += 1;
670 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
671 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
677 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
678 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
679 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
683 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
685 $aSearch = $aCurrentSearch;
686 $aSearch['iSearchRank'] += 1;
687 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
688 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
689 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
690 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
692 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
693 $aSearch['iNamePhrase'] = $iPhrase;
694 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
701 // Allow skipping a word - but at EXTREAM cost
702 //$aSearch = $aCurrentSearch;
703 //$aSearch['iSearchRank']+=100;
704 //$aNewWordsetSearches[] = $aSearch;
708 usort($aNewWordsetSearches, 'bySearchRank');
709 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
711 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
713 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
714 usort($aNewPhraseSearches, 'bySearchRank');
716 $aSearchHash = array();
717 foreach($aNewPhraseSearches as $iSearch => $aSearch)
719 $sHash = serialize($aSearch);
720 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
721 else $aSearchHash[$sHash] = 1;
724 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
727 // Re-group the searches by their score, junk anything over 20 as just not worth trying
728 $aGroupedSearches = array();
729 foreach($aNewPhraseSearches as $aSearch)
731 if ($aSearch['iSearchRank'] < $this->iMaxRank)
733 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
734 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
737 ksort($aGroupedSearches);
740 $aSearches = array();
741 foreach($aGroupedSearches as $iScore => $aNewSearches)
743 $iSearchCount += sizeof($aNewSearches);
744 $aSearches = array_merge($aSearches, $aNewSearches);
745 if ($iSearchCount > 50) break;
748 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
751 return $aGroupedSearches;
755 /* Perform the actual query lookup.
757 Returns an ordered list of results, each with the following fields:
758 osm_type: type of corresponding OSM object
762 P - postcode (internally computed)
763 osm_id: id of corresponding OSM object
764 class: general object class (corresponds to tag key of primary OSM tag)
765 type: subclass of object (corresponds to tag value of primary OSM tag)
766 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
767 rank_search: rank in search hierarchy
768 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
769 rank_address: rank in address hierarchy (determines orer in address)
770 place_id: internal key (may differ between different instances)
771 country_code: ISO country code
772 langaddress: localized full address
773 placename: localized name of object
774 ref: content of ref tag (if available)
777 importance: importance of place based on Wikipedia link count
778 addressimportance: cumulated importance of address elements
779 extra_place: type of place (for admin boundaries, if there is a place tag)
780 aBoundingBox: bounding Box
781 label: short description of the object class/type (English only)
782 name: full name (currently the same as langaddress)
783 foundorder: secondary ordering for places with same importance
787 if (!$this->sQuery && !$this->aStructuredQuery) return false;
789 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
790 $sCountryCodesSQL = false;
791 if ($this->aCountryCodes && sizeof($this->aCountryCodes))
793 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
796 $sQuery = $this->sQuery;
798 // Conflicts between US state abreviations and various words for 'the' in different languages
799 if (isset($this->aLangPrefOrder['name:en']))
801 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/','\1illinois\2', $sQuery);
802 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery);
803 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery);
807 $sViewboxCentreSQL = false;
808 $bBoundingBoxSearch = false;
811 $fHeight = $this->aViewBox[0]-$this->aViewBox[2];
812 $fWidth = $this->aViewBox[1]-$this->aViewBox[3];
813 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
814 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
815 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
816 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
818 $this->sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$this->aViewBox[0].",".(float)$this->aViewBox[1]."),ST_Point(".(float)$this->aViewBox[2].",".(float)$this->aViewBox[3].")),4326)";
819 $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aBigViewBox[0].",".(float)$aBigViewBox[1]."),ST_Point(".(float)$aBigViewBox[2].",".(float)$aBigViewBox[3].")),4326)";
820 $bBoundingBoxSearch = $this->bBoundedSearch;
824 if ($this->aRoutePoints)
826 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
828 foreach($this->aRoutePoints as $aPoint)
830 if (!$bFirst) $sViewboxCentreSQL .= ",";
831 $sViewboxCentreSQL .= $aPoint[0].' '.$aPoint[1];
834 $sViewboxCentreSQL .= ")'::geometry,4326)";
836 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
837 $this->sViewboxSmallSQL = $this->oDB->getOne($sSQL);
838 if (PEAR::isError($this->sViewboxSmallSQL))
840 failInternalError("Could not get small viewbox.", $sSQL, $this->sViewboxSmallSQL);
842 $this->sViewboxSmallSQL = "'".$this->sViewboxSmallSQL."'::geometry";
844 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
845 $this->sViewboxLargeSQL = $this->oDB->getOne($sSQL);
846 if (PEAR::isError($this->sViewboxLargeSQL))
848 failInternalError("Could not get large viewbox.", $sSQL, $this->sViewboxLargeSQL);
850 $this->sViewboxLargeSQL = "'".$this->sViewboxLargeSQL."'::geometry";
851 $bBoundingBoxSearch = $this->bBoundedSearch;
854 // Do we have anything that looks like a lat/lon pair?
855 if ( $aLooksLike = looksLikeLatLonPair($sQuery) ){
856 $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
857 $sQuery = $aLooksLike['query'];
860 $aSearchResults = array();
861 if ($sQuery || $this->aStructuredQuery)
863 // Start with a blank search
865 array('iSearchRank' => 0,
867 'sCountryCode' => false,
869 'aAddress' => array(),
870 'aFullNameAddress' => array(),
871 'aNameNonSearch' => array(),
872 'aAddressNonSearch' => array(),
874 'aFeatureName' => array(),
877 'sHouseNumber' => '',
884 // Do we have a radius search?
885 $sNearPointSQL = false;
886 if ($this->aNearPoint)
888 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
889 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
890 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
891 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
894 // Any 'special' terms in the search?
895 $bSpecialTerms = false;
896 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
897 $aSpecialTerms = array();
898 foreach($aSpecialTermsRaw as $aSpecialTerm)
900 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
901 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
904 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
905 $aSpecialTerms = array();
906 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity'])
908 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
909 unset($this->aStructuredQuery['amenity']);
911 foreach($aSpecialTermsRaw as $aSpecialTerm)
913 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
914 $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
915 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
916 $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';
917 if (CONST_Debug) var_Dump($sSQL);
918 $aSearchWords = $this->oDB->getAll($sSQL);
919 $aNewSearches = array();
920 foreach($aSearches as $aSearch)
922 foreach($aSearchWords as $aSearchTerm)
924 $aNewSearch = $aSearch;
925 if ($aSearchTerm['country_code'])
927 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
928 $aNewSearches[] = $aNewSearch;
929 $bSpecialTerms = true;
931 if ($aSearchTerm['class'])
933 $aNewSearch['sClass'] = $aSearchTerm['class'];
934 $aNewSearch['sType'] = $aSearchTerm['type'];
935 $aNewSearches[] = $aNewSearch;
936 $bSpecialTerms = true;
940 $aSearches = $aNewSearches;
943 // Split query into phrases
944 // Commas are used to reduce the search space by indicating where phrases split
945 if ($this->aStructuredQuery)
947 $aPhrases = $this->aStructuredQuery;
948 $bStructuredPhrases = true;
952 $aPhrases = explode(',',$sQuery);
953 $bStructuredPhrases = false;
956 // Convert each phrase to standard form
957 // Create a list of standard words
958 // Get all 'sets' of words
959 // Generate a complete list of all
961 foreach($aPhrases as $iPhrase => $sPhrase)
963 $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
964 if (PEAR::isError($aPhrase))
966 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
967 if (CONST_Debug) var_dump($aPhrase);
970 if (trim($aPhrase['string']))
972 $aPhrases[$iPhrase] = $aPhrase;
973 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
974 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
975 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
979 unset($aPhrases[$iPhrase]);
983 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
984 $aPhraseTypes = array_keys($aPhrases);
985 $aPhrases = array_values($aPhrases);
987 if (sizeof($aTokens))
989 // Check which tokens we have, get the ID numbers
990 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
991 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
993 if (CONST_Debug) var_Dump($sSQL);
995 $aValidTokens = array();
996 if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL);
997 else $aDatabaseWords = array();
998 if (PEAR::IsError($aDatabaseWords))
1000 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
1002 $aPossibleMainWordIDs = array();
1003 $aWordFrequencyScores = array();
1004 foreach($aDatabaseWords as $aToken)
1006 // Very special case - require 2 letter country param to match the country code found
1007 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1008 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code'])
1013 if (isset($aValidTokens[$aToken['word_token']]))
1015 $aValidTokens[$aToken['word_token']][] = $aToken;
1019 $aValidTokens[$aToken['word_token']] = array($aToken);
1021 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1022 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1024 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1026 // Try and calculate GB postcodes we might be missing
1027 foreach($aTokens as $sToken)
1029 // Source of gb postcodes is now definitive - always use
1030 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
1032 if (substr($aData[1],-2,1) != ' ')
1034 $aData[0] = substr($aData[0],0,strlen($aData[1])-1).' '.substr($aData[0],strlen($aData[1])-1);
1035 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
1037 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1038 if ($aGBPostcodeLocation)
1040 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1043 // US ZIP+4 codes - if there is no token,
1044 // merge in the 5-digit ZIP code
1045 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
1047 if (isset($aValidTokens[$aData[1]]))
1049 foreach($aValidTokens[$aData[1]] as $aToken)
1051 if (!$aToken['class'])
1053 if (isset($aValidTokens[$sToken]))
1055 $aValidTokens[$sToken][] = $aToken;
1059 $aValidTokens[$sToken] = array($aToken);
1067 foreach($aTokens as $sToken)
1069 // Unknown single word token with a number - assume it is a house number
1070 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
1072 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
1076 // Any words that have failed completely?
1077 // TODO: suggestions
1079 // Start the search process
1080 $aResultPlaceIDs = array();
1082 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
1084 if ($this->bReverseInPlan)
1086 // Reverse phrase array and also reverse the order of the wordsets in
1087 // the first and final phrase. Don't bother about phrases in the middle
1088 // because order in the address doesn't matter.
1089 $aPhrases = array_reverse($aPhrases);
1090 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1091 if (sizeof($aPhrases) > 1)
1093 $aFinalPhrase = end($aPhrases);
1094 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1096 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1098 foreach($aGroupedSearches as $aSearches)
1100 foreach($aSearches as $aSearch)
1102 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1104 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1105 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1111 $aGroupedSearches = $aReverseGroupedSearches;
1112 ksort($aGroupedSearches);
1117 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1118 $aGroupedSearches = array();
1119 foreach($aSearches as $aSearch)
1121 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1123 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1124 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1127 ksort($aGroupedSearches);
1130 if (CONST_Debug) var_Dump($aGroupedSearches);
1132 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0)
1134 $aCopyGroupedSearches = $aGroupedSearches;
1135 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
1137 foreach($aSearches as $iSearch => $aSearch)
1139 $aReductionsList = array($aSearch['aAddress']);
1140 $iSearchRank = $aSearch['iSearchRank'];
1141 while(sizeof($aReductionsList) > 0)
1144 if ($iSearchRank > iMaxRank) break 3;
1145 $aNewReductionsList = array();
1146 foreach($aReductionsList as $aReductionsWordList)
1148 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
1150 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1151 $aReverseSearch = $aSearch;
1152 $aSearch['aAddress'] = $aReductionsWordListResult;
1153 $aSearch['iSearchRank'] = $iSearchRank;
1154 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1155 if (sizeof($aReductionsWordListResult) > 0)
1157 $aNewReductionsList[] = $aReductionsWordListResult;
1161 $aReductionsList = $aNewReductionsList;
1165 ksort($aGroupedSearches);
1168 // Filter out duplicate searches
1169 $aSearchHash = array();
1170 foreach($aGroupedSearches as $iGroup => $aSearches)
1172 foreach($aSearches as $iSearch => $aSearch)
1174 $sHash = serialize($aSearch);
1175 if (isset($aSearchHash[$sHash]))
1177 unset($aGroupedSearches[$iGroup][$iSearch]);
1178 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1182 $aSearchHash[$sHash] = 1;
1187 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1191 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
1194 foreach($aSearches as $aSearch)
1198 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
1199 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1201 // No location term?
1202 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
1204 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
1206 // Just looking for a country by code - look it up
1207 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
1209 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1210 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1211 if ($bBoundingBoxSearch)
1212 $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
1213 $sSQL .= " order by st_area(geometry) desc limit 1";
1214 if (CONST_Debug) var_dump($sSQL);
1215 $aPlaceIDs = $this->oDB->getCol($sSQL);
1219 $aPlaceIDs = array();
1224 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1225 if (!$aSearch['sClass']) continue;
1226 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1227 if ($this->oDB->getOne($sSQL))
1229 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1230 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1231 $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1232 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1233 if (sizeof($this->aExcludePlaceIDs))
1235 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1237 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1238 $sSQL .= " limit $this->iLimit";
1239 if (CONST_Debug) var_dump($sSQL);
1240 $aPlaceIDs = $this->oDB->getCol($sSQL);
1242 // If excluded place IDs are given, it is fair to assume that
1243 // there have been results in the small box, so no further
1244 // expansion in that case.
1245 // Also don't expand if bounded results were requested.
1246 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch)
1248 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1249 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1250 $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1251 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1252 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1253 $sSQL .= " limit $this->iLimit";
1254 if (CONST_Debug) var_dump($sSQL);
1255 $aPlaceIDs = $this->oDB->getCol($sSQL);
1260 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1261 $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1262 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1263 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
1264 $sSQL .= " limit $this->iLimit";
1265 if (CONST_Debug) var_dump($sSQL);
1266 $aPlaceIDs = $this->oDB->getCol($sSQL);
1272 $aPlaceIDs = array();
1274 // First we need a position, either aName or fLat or both
1278 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress']))
1280 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1281 $aOrder[] = "exists(select place_id from placex where parent_place_id = search_name.place_id and transliteration(housenumber) ~* E'".$sHouseNumberRegex."' limit 1) desc";
1284 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1285 // they might be right - but they are just too darned expensive to run
1286 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
1287 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
1288 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
1290 // For infrequent name terms disable index usage for address
1291 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
1292 sizeof($aSearch['aName']) == 1 &&
1293 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
1295 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
1299 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
1300 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
1303 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1304 if ($aSearch['sHouseNumber'])
1306 $aTerms[] = "address_rank between 16 and 27";
1310 if ($this->iMinAddressRank > 0)
1312 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1314 if ($this->iMaxAddressRank < 30)
1316 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1319 if ($aSearch['fLon'] && $aSearch['fLat'])
1321 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1322 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1324 if (sizeof($this->aExcludePlaceIDs))
1326 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1328 if ($sCountryCodesSQL)
1330 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1333 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1334 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1336 if ($aSearch['sHouseNumber'])
1338 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1342 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1344 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1345 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1347 $aOrder[] = "$sImportanceSQL DESC";
1348 if (sizeof($aSearch['aFullNameAddress']))
1350 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1351 $aOrder[] = 'exactmatch DESC';
1353 $sExactMatchSQL = '0::int as exactmatch';
1356 if (sizeof($aTerms))
1358 $sSQL = "select place_id, ";
1359 $sSQL .= $sExactMatchSQL;
1360 $sSQL .= " from search_name";
1361 $sSQL .= " where ".join(' and ',$aTerms);
1362 $sSQL .= " order by ".join(', ',$aOrder);
1363 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
1364 $sSQL .= " limit 20";
1365 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
1366 $sSQL .= " limit 1";
1368 $sSQL .= " limit ".$this->iLimit;
1370 if (CONST_Debug) { var_dump($sSQL); }
1371 $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL);
1372 if (PEAR::IsError($aViewBoxPlaceIDs))
1374 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
1376 //var_dump($aViewBoxPlaceIDs);
1377 // Did we have an viewbox matches?
1378 $aPlaceIDs = array();
1379 $bViewBoxMatch = false;
1380 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
1382 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1383 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1384 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1385 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1386 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1387 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1390 //var_Dump($aPlaceIDs);
1393 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1395 $aRoadPlaceIDs = $aPlaceIDs;
1396 $sPlaceIDs = join(',',$aPlaceIDs);
1398 // Now they are indexed look for a house attached to a street we found
1399 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1400 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1401 if (sizeof($this->aExcludePlaceIDs))
1403 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1405 $sSQL .= " limit $this->iLimit";
1406 if (CONST_Debug) var_dump($sSQL);
1407 $aPlaceIDs = $this->oDB->getCol($sSQL);
1409 // If not try the aux fallback table
1410 if (!sizeof($aPlaceIDs))
1412 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1413 if (sizeof($this->aExcludePlaceIDs))
1415 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1417 //$sSQL .= " limit $this->iLimit";
1418 if (CONST_Debug) var_dump($sSQL);
1419 $aPlaceIDs = $this->oDB->getCol($sSQL);
1422 if (!sizeof($aPlaceIDs))
1424 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1425 if (sizeof($this->aExcludePlaceIDs))
1427 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1429 //$sSQL .= " limit $this->iLimit";
1430 if (CONST_Debug) var_dump($sSQL);
1431 $aPlaceIDs = $this->oDB->getCol($sSQL);
1434 // Fallback to the road
1435 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1437 $aPlaceIDs = $aRoadPlaceIDs;
1442 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1444 $sPlaceIDs = join(',',$aPlaceIDs);
1445 $aClassPlaceIDs = array();
1447 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1449 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1450 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1451 $sSQL .= " and linked_place_id is null";
1452 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1453 $sSQL .= " order by rank_search asc limit $this->iLimit";
1454 if (CONST_Debug) var_dump($sSQL);
1455 $aClassPlaceIDs = $this->oDB->getCol($sSQL);
1458 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1460 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1461 $bCacheTable = $this->oDB->getOne($sSQL);
1463 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1465 if (CONST_Debug) var_dump($sSQL);
1466 $this->iMaxRank = ((int)$this->oDB->getOne($sSQL));
1468 // For state / country level searches the normal radius search doesn't work very well
1469 $sPlaceGeom = false;
1470 if ($this->iMaxRank < 9 && $bCacheTable)
1472 // Try and get a polygon to search in instead
1473 $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";
1474 if (CONST_Debug) var_dump($sSQL);
1475 $sPlaceGeom = $this->oDB->getOne($sSQL);
1484 $this->iMaxRank += 5;
1485 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1486 if (CONST_Debug) var_dump($sSQL);
1487 $aPlaceIDs = $this->oDB->getCol($sSQL);
1488 $sPlaceIDs = join(',',$aPlaceIDs);
1491 if ($sPlaceIDs || $sPlaceGeom)
1497 // More efficient - can make the range bigger
1501 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1502 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1503 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1505 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1506 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1509 $sSQL .= ",placex as f where ";
1510 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1515 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1517 if (sizeof($this->aExcludePlaceIDs))
1519 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1521 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1522 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1523 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1524 $sSQL .= " limit $this->iLimit";
1525 if (CONST_Debug) var_dump($sSQL);
1526 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1530 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1533 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1534 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1536 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1537 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1538 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1539 if (sizeof($this->aExcludePlaceIDs))
1541 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1543 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1544 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1545 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1546 $sSQL .= " limit $this->iLimit";
1547 if (CONST_Debug) var_dump($sSQL);
1548 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1553 $aPlaceIDs = $aClassPlaceIDs;
1559 if (PEAR::IsError($aPlaceIDs))
1561 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1564 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1566 foreach($aPlaceIDs as $iPlaceID)
1568 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1570 if ($iQueryLoop > 20) break;
1573 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
1575 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1576 $sSQL = "select place_id from placex where place_id in (".join(',',$aResultPlaceIDs).") ";
1577 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1578 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1579 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
1580 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',$aResultPlaceIDs).") ";
1581 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1582 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
1584 if (CONST_Debug) var_dump($sSQL);
1585 $aResultPlaceIDs = $this->oDB->getCol($sSQL);
1589 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1590 if ($iGroupLoop > 4) break;
1591 if ($iQueryLoop > 30) break;
1594 // Did we find anything?
1595 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1597 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1603 // Just interpret as a reverse geocode
1604 $iPlaceID = geocodeReverse((float)$this->aNearPoint[0], (float)$this->aNearPoint[1]);
1606 $aSearchResults = $this->getDetails(array($iPlaceID));
1608 $aSearchResults = array();
1612 if (!sizeof($aSearchResults))
1614 if ($this->bFallback)
1616 if ($this->fallbackStructuredQuery())
1618 return $this->lookup();
1625 $aClassType = getClassTypesWithImportance();
1626 $aRecheckWords = preg_split('/\b[\s,\\-]*/u',$sQuery);
1627 foreach($aRecheckWords as $i => $sWord)
1629 if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1632 if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
1634 foreach($aSearchResults as $iResNum => $aResult)
1637 $fDiameter = 0.0001;
1639 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1640 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1642 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
1644 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1645 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1647 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1649 $fRadius = $fDiameter / 2;
1651 if (CONST_Search_AreaPolygons)
1653 // Get the bounding box and outline polygon
1654 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1655 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1656 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
1657 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
1658 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1659 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1660 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1661 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
1662 $sFrom = " from placex where place_id = ".$aResult['place_id'];
1663 if ($this->fPolygonSimplificationThreshold > 0)
1665 $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
1672 $aPointPolygon = $this->oDB->getRow($sSQL);
1673 if (PEAR::IsError($aPointPolygon))
1675 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1678 if ($aPointPolygon['place_id'])
1680 if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1681 if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1682 if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1683 if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
1685 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1687 $aResult['lat'] = $aPointPolygon['centrelat'];
1688 $aResult['lon'] = $aPointPolygon['centrelon'];
1691 if ($this->bIncludePolygonAsPoints)
1693 $aPolyPoints[] = geometryText2Points($aPointPolygon['astext'],$fRadius);
1695 // Output data suitable for display (points and a bounding box)
1696 if (isset($aPolyPoints))
1698 $aResult['aPolyPoints'] = array();
1699 foreach($aPolyPoints as $aPoint)
1701 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1706 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
1708 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1709 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1711 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
1713 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1714 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1716 $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
1720 if ($aResult['extra_place'] == 'city')
1722 $aResult['class'] = 'place';
1723 $aResult['type'] = 'city';
1724 $aResult['rank_search'] = 16;
1727 if (!isset($aResult['aBoundingBox']))
1729 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1730 $fStepSize = (2*pi())/$iSteps;
1731 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1732 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1733 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1734 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1736 // Output data suitable for display (points and a bounding box)
1737 if ($this->bIncludePolygonAsPoints)
1739 $aPolyPoints = array();
1740 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1742 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1744 $aResult['aPolyPoints'] = array();
1745 foreach($aPolyPoints as $aPoint)
1747 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1750 $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
1753 // Is there an icon set for this type of result?
1754 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1755 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1757 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1760 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1761 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1763 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1765 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1766 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1768 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1771 if ($this->bIncludeAddressDetails)
1773 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1774 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1776 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1780 if ($this->bIncludeExtraTags)
1782 if ($aResult['extra'])
1784 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1788 $aResult['sExtraTags'] = (object) array();
1792 if ($this->bIncludeNameDetails)
1794 if ($aResult['names'])
1796 $aResult['sNameDetails'] = json_decode($aResult['names']);
1800 $aResult['sNameDetails'] = (object) array();
1804 // Adjust importance for the number of exact string matches in the result
1805 $aResult['importance'] = max(0.001,$aResult['importance']);
1807 $sAddress = $aResult['langaddress'];
1808 foreach($aRecheckWords as $i => $sWord)
1810 if (stripos($sAddress, $sWord)!==false)
1813 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1817 $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
1819 $aResult['name'] = $aResult['langaddress'];
1820 // secondary ordering (for results with same importance (the smaller the better):
1821 // - approximate importance of address parts
1822 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1823 // - number of exact matches from the query
1824 if (isset($this->exactMatchCache[$aResult['place_id']]))
1825 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1826 else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
1827 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1828 // - importance of the class/type
1829 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1830 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1832 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1836 $aResult['foundorder'] += 0.01;
1838 if (CONST_Debug) { var_dump($aResult); }
1839 $aSearchResults[$iResNum] = $aResult;
1841 uasort($aSearchResults, 'byImportance');
1843 $aOSMIDDone = array();
1844 $aClassTypeNameDone = array();
1845 $aToFilter = $aSearchResults;
1846 $aSearchResults = array();
1849 foreach($aToFilter as $iResNum => $aResult)
1851 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1854 $fLat = $aResult['lat'];
1855 $fLon = $aResult['lon'];
1856 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1859 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1860 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1862 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1863 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1864 $aSearchResults[] = $aResult;
1867 // Absolute limit on number of results
1868 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1871 return $aSearchResults;