6 protected $aLangPrefOrder = array();
8 protected $bIncludeAddressDetails = false;
10 protected $bIncludePolygonAsPoints = false;
11 protected $bIncludePolygonAsText = false;
12 protected $bIncludePolygonAsGeoJSON = false;
13 protected $bIncludePolygonAsKML = false;
14 protected $bIncludePolygonAsSVG = false;
15 protected $fPolygonSimplificationThreshold = 0.0;
17 protected $aExcludePlaceIDs = array();
18 protected $bDeDupe = true;
19 protected $bReverseInPlan = true;
21 protected $iLimit = 20;
22 protected $iFinalLimit = 10;
23 protected $iOffset = 0;
24 protected $bFallback = false;
26 protected $aCountryCodes = false;
27 protected $aNearPoint = false;
29 protected $bBoundedSearch = false;
30 protected $aViewBox = false;
31 protected $sViewboxSmallSQL = false;
32 protected $sViewboxLargeSQL = false;
33 protected $aRoutePoints = false;
35 protected $iMaxRank = 20;
36 protected $iMinAddressRank = 0;
37 protected $iMaxAddressRank = 30;
38 protected $aAddressRankList = array();
39 protected $exactMatchCache = array();
41 protected $sAllowedTypesSQLList = false;
43 protected $sQuery = false;
44 protected $aStructuredQuery = false;
46 function Geocode(&$oDB)
51 function setReverseInPlan($bReverse)
53 $this->bReverseInPlan = $bReverse;
56 function setLanguagePreference($aLangPref)
58 $this->aLangPrefOrder = $aLangPref;
61 function setIncludeAddressDetails($bAddressDetails = true)
63 $this->bIncludeAddressDetails = (bool)$bAddressDetails;
66 function getIncludeAddressDetails()
68 return $this->bIncludeAddressDetails;
71 function setIncludePolygonAsPoints($b = true)
73 $this->bIncludePolygonAsPoints = $b;
76 function getIncludePolygonAsPoints()
78 return $this->bIncludePolygonAsPoints;
81 function setIncludePolygonAsText($b = true)
83 $this->bIncludePolygonAsText = $b;
86 function getIncludePolygonAsText()
88 return $this->bIncludePolygonAsText;
91 function setIncludePolygonAsGeoJSON($b = true)
93 $this->bIncludePolygonAsGeoJSON = $b;
96 function setIncludePolygonAsKML($b = true)
98 $this->bIncludePolygonAsKML = $b;
101 function setIncludePolygonAsSVG($b = true)
103 $this->bIncludePolygonAsSVG = $b;
106 function setPolygonSimplificationThreshold($f)
108 $this->fPolygonSimplificationThreshold = $f;
111 function setDeDupe($bDeDupe = true)
113 $this->bDeDupe = (bool)$bDeDupe;
116 function setLimit($iLimit = 10)
118 if ($iLimit > 50) $iLimit = 50;
119 if ($iLimit < 1) $iLimit = 1;
121 $this->iFinalLimit = $iLimit;
122 $this->iLimit = $this->iFinalLimit + min($this->iFinalLimit, 10);
125 function setOffset($iOffset = 0)
127 $this->iOffset = $iOffset;
130 function setFallback($bFallback = true)
132 $this->bFallback = (bool)$bFallback;
135 function setExcludedPlaceIDs($a)
137 // TODO: force to int
138 $this->aExcludePlaceIDs = $a;
141 function getExcludedPlaceIDs()
143 return $this->aExcludePlaceIDs;
146 function setBounded($bBoundedSearch = true)
148 $this->bBoundedSearch = (bool)$bBoundedSearch;
151 function setViewBox($sLeft, $sBottom, $sRight, $sTop)
153 $fLeft = (float)$sLeft;
154 $fRight = (float)$sRight;
155 $fTop = (float)$sTop;
156 $fBottom = (float)$sBottom;
157 if ($fRight > $fLeft && $fBottom < $fTop
158 && ($fRight - $fLeft) < 2 && ($fTop - $fBottom) < 2)
159 $this->aViewBox = array($fLeft, $fBottom, $fRight, $fTop);
162 function getViewBoxString()
164 if (!$this->aViewBox) return null;
165 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
168 function setRoute($aRoutePoints)
170 $this->aRoutePoints = $aRoutePoints;
173 function setFeatureType($sFeatureType)
175 switch($sFeatureType)
178 $this->setRankRange(4, 4);
181 $this->setRankRange(8, 8);
184 $this->setRankRange(14, 16);
187 $this->setRankRange(8, 20);
192 function setRankRange($iMin, $iMax)
194 $this->iMinAddressRank = (int)$iMin;
195 $this->iMaxAddressRank = (int)$iMax;
198 function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
200 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
203 function setCountryCodesList($aCountryCodes)
205 $this->aCountryCodes = $aCountryCodes;
208 function setQuery($sQueryString)
210 $this->sQuery = $sQueryString;
211 $this->aStructuredQuery = false;
214 function getQueryString()
216 return $this->sQuery;
220 function loadParamArray($aParams)
222 if (isset($aParams['addressdetails'])) $this->bIncludeAddressDetails = (bool)$aParams['addressdetails'];
223 if (isset($aParams['bounded'])) $this->bBoundedSearch = (bool)$aParams['bounded'];
224 if (isset($aParams['dedupe'])) $this->bDeDupe = (bool)$aParams['dedupe'];
226 if (isset($aParams['limit'])) $this->setLimit((int)$aParams['limit']);
227 if (isset($aParams['offset'])) $this->iOffset = (int)$aParams['offset'];
229 if (isset($aParams['fallback'])) $this->bFallback = (bool)$aParams['fallback'];
231 // List of excluded Place IDs - used for more acurate pageing
232 if (isset($aParams['exclude_place_ids']) && $aParams['exclude_place_ids'])
234 foreach(explode(',',$aParams['exclude_place_ids']) as $iExcludedPlaceID)
236 $iExcludedPlaceID = (int)$iExcludedPlaceID;
237 if ($iExcludedPlaceID)
238 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
241 if (isset($aExcludePlaceIDs))
242 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
245 // Only certain ranks of feature
246 if (isset($aParams['featureType'])) $this->setFeatureType($aParams['featureType']);
247 if (isset($aParams['featuretype'])) $this->setFeatureType($aParams['featuretype']);
250 if (isset($aParams['countrycodes']))
252 $aCountryCodes = array();
253 foreach(explode(',',$aParams['countrycodes']) as $sCountryCode)
255 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
257 $aCountryCodes[] = strtolower($sCountryCode);
260 $this->aCountryCodes = $aCountryCodes;
263 if (isset($aParams['viewboxlbrt']) && $aParams['viewboxlbrt'])
265 $aCoOrdinatesLBRT = explode(',',$aParams['viewboxlbrt']);
266 $this->setViewBox($aCoOrdinatesLBRT[0], $aCoOrdinatesLBRT[1], $aCoOrdinatesLBRT[2], $aCoOrdinatesLBRT[3]);
268 else if (isset($aParams['viewbox']) && $aParams['viewbox'])
270 $aCoOrdinatesLTRB = explode(',',$aParams['viewbox']);
271 $this->setViewBox($aCoOrdinatesLTRB[0], $aCoOrdinatesLTRB[3], $aCoOrdinatesLTRB[2], $aCoOrdinatesLTRB[1]);
274 if (isset($aParams['route']) && $aParams['route'] && isset($aParams['routewidth']) && $aParams['routewidth'])
276 $aPoints = explode(',',$aParams['route']);
277 if (sizeof($aPoints) % 2 != 0)
279 userError("Uneven number of points");
284 foreach($aPoints as $i => $fPoint)
288 $aRoute[] = array((float)$fPoint, $fPrevCoord);
292 $fPrevCoord = (float)$fPoint;
295 $this->aRoutePoints = $aRoute;
299 function setQueryFromParams($aParams)
302 $sQuery = (isset($aParams['q'])?trim($aParams['q']):'');
305 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
306 $this->setReverseInPlan(false);
310 $this->setQuery($sQuery);
314 function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
316 $sValue = trim($sValue);
317 if (!$sValue) return false;
318 $this->aStructuredQuery[$sKey] = $sValue;
319 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30)
321 $this->iMinAddressRank = $iNewMinAddressRank;
322 $this->iMaxAddressRank = $iNewMaxAddressRank;
324 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
328 function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
330 $this->sQuery = false;
333 $this->iMinAddressRank = 0;
334 $this->iMaxAddressRank = 30;
335 $this->aAddressRankList = array();
337 $this->aStructuredQuery = array();
338 $this->sAllowedTypesSQLList = '';
340 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
341 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
342 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
343 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
344 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
345 $this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11));
346 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
348 if (sizeof($this->aStructuredQuery) > 0)
350 $this->sQuery = join(', ', $this->aStructuredQuery);
351 if ($this->iMaxAddressRank < 30)
353 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
358 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)
370 if (isset($aParams[$sType]))
372 unset($aParams[$sType]);
373 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
381 function getDetails($aPlaceIDs)
383 if (sizeof($aPlaceIDs) == 0) return array();
385 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
387 // Get the details for display (is this a redundant extra step?)
388 $sPlaceIDs = join(',',$aPlaceIDs);
390 $sImportanceSQL = '';
391 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
392 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
394 $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,";
395 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
396 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
397 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
398 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
399 $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
400 $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, ";
401 $sSQL .= "(extratags->'place') as extra_place ";
402 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
403 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
404 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
405 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
407 if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
408 $sSQL .= "and linked_place_id is null ";
409 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
410 if (!$this->bDeDupe) $sSQL .= ",place_id";
411 $sSQL .= ",langaddress ";
412 $sSQL .= ",placename ";
414 $sSQL .= ",extratags->'place' ";
416 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
419 $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,";
420 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
421 $sSQL .= "null as placename,";
422 $sSQL .= "null as ref,";
423 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
424 $sSQL .= $sImportanceSQL."-1.15 as importance, ";
425 $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, ";
426 $sSQL .= "null as extra_place ";
427 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
428 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
429 $sSQL .= "group by place_id";
430 if (!$this->bDeDupe) $sSQL .= ",place_id ";
433 $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,";
434 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
435 $sSQL .= "null as placename,";
436 $sSQL .= "null as ref,";
437 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
438 $sSQL .= $sImportanceSQL."-1.10 as importance, ";
439 $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, ";
440 $sSQL .= "null as extra_place ";
441 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
442 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
443 $sSQL .= "group by place_id";
444 if (!$this->bDeDupe) $sSQL .= ",place_id";
445 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
449 $sSQL .= " order by importance desc";
450 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
451 $aSearchResults = $this->oDB->getAll($sSQL);
453 if (PEAR::IsError($aSearchResults))
455 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
458 return $aSearchResults;
461 function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
464 Calculate all searches using aValidTokens i.e.
465 'Wodsworth Road, Sheffield' =>
469 0 1 (wodsworth)(road)
472 Score how good the search is so they can be ordered
474 foreach($aPhrases as $iPhrase => $sPhrase)
476 $aNewPhraseSearches = array();
477 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
478 else $sPhraseType = '';
480 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
482 // Too many permutations - too expensive
483 if ($iWordSet > 120) break;
485 $aWordsetSearches = $aSearches;
487 // Add all words from this wordset
488 foreach($aWordset as $iToken => $sToken)
490 //echo "<br><b>$sToken</b>";
491 $aNewWordsetSearches = array();
493 foreach($aWordsetSearches as $aCurrentSearch)
496 //var_dump($aCurrentSearch);
499 // If the token is valid
500 if (isset($aValidTokens[' '.$sToken]))
502 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
504 $aSearch = $aCurrentSearch;
505 $aSearch['iSearchRank']++;
506 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
508 if ($aSearch['sCountryCode'] === false)
510 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
511 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
512 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)))
514 $aSearch['iSearchRank'] += 5;
516 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
519 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
521 if ($aSearch['fLat'] === '')
523 $aSearch['fLat'] = $aSearchTerm['lat'];
524 $aSearch['fLon'] = $aSearchTerm['lon'];
525 $aSearch['fRadius'] = $aSearchTerm['radius'];
526 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
529 elseif ($sPhraseType == 'postalcode')
531 // 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
532 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
534 // If we already have a name try putting the postcode first
535 if (sizeof($aSearch['aName']))
537 $aNewSearch = $aSearch;
538 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
539 $aNewSearch['aName'] = array();
540 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
541 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
544 if (sizeof($aSearch['aName']))
546 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
548 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
552 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
553 $aSearch['iSearchRank'] += 1000; // skip;
558 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
559 //$aSearch['iNamePhrase'] = $iPhrase;
561 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
565 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
567 if ($aSearch['sHouseNumber'] === '')
569 $aSearch['sHouseNumber'] = $sToken;
570 // sanity check: if the housenumber is not mainly made
571 // up of numbers, add a penalty
572 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
573 // also housenumbers should appear in the first or second phrase
574 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
575 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
577 // Fall back to not searching for this item (better than nothing)
578 $aSearch = $aCurrentSearch;
579 $aSearch['iSearchRank'] += 1;
580 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
584 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
586 if ($aSearch['sClass'] === '')
588 $aSearch['sOperator'] = $aSearchTerm['operator'];
589 $aSearch['sClass'] = $aSearchTerm['class'];
590 $aSearch['sType'] = $aSearchTerm['type'];
591 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
592 else $aSearch['sOperator'] = 'near'; // near = in for the moment
593 if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
595 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
598 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
600 if (sizeof($aSearch['aName']))
602 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
604 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
608 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
609 $aSearch['iSearchRank'] += 1000; // skip;
614 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
615 //$aSearch['iNamePhrase'] = $iPhrase;
617 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
621 // Look for partial matches.
622 // Note that there is no point in adding country terms here
623 // because country are omitted in the address.
624 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country')
626 // Allow searching for a word - but at extra cost
627 foreach($aValidTokens[$sToken] as $aSearchTerm)
629 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
631 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false)
633 $aSearch = $aCurrentSearch;
634 $aSearch['iSearchRank'] += 1;
635 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
637 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
638 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
640 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
642 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
643 $aSearch['iSearchRank'] += 1;
644 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
645 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
647 if (empty($aSearchTermToken['country_code'])
648 && empty($aSearchTermToken['lat'])
649 && empty($aSearchTermToken['class']))
651 $aSearch = $aCurrentSearch;
652 $aSearch['iSearchRank'] += 1;
653 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
654 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
660 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
661 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
662 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
666 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
668 $aSearch = $aCurrentSearch;
669 $aSearch['iSearchRank'] += 1;
670 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
671 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
672 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
673 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
675 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
676 $aSearch['iNamePhrase'] = $iPhrase;
677 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)
702 $sHash = serialize($aSearch);
703 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
704 else $aSearchHash[$sHash] = 1;
707 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
710 // Re-group the searches by their score, junk anything over 20 as just not worth trying
711 $aGroupedSearches = array();
712 foreach($aNewPhraseSearches as $aSearch)
714 if ($aSearch['iSearchRank'] < $this->iMaxRank)
716 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
717 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
720 ksort($aGroupedSearches);
723 $aSearches = array();
724 foreach($aGroupedSearches as $iScore => $aNewSearches)
726 $iSearchCount += sizeof($aNewSearches);
727 $aSearches = array_merge($aSearches, $aNewSearches);
728 if ($iSearchCount > 50) break;
731 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
734 return $aGroupedSearches;
738 /* Perform the actual query lookup.
740 Returns an ordered list of results, each with the following fields:
741 osm_type: type of corresponding OSM object
745 P - postcode (internally computed)
746 osm_id: id of corresponding OSM object
747 class: general object class (corresponds to tag key of primary OSM tag)
748 type: subclass of object (corresponds to tag value of primary OSM tag)
749 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
750 rank_search: rank in search hierarchy
751 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
752 rank_address: rank in address hierarchy (determines orer in address)
753 place_id: internal key (may differ between different instances)
754 country_code: ISO country code
755 langaddress: localized full address
756 placename: localized name of object
757 ref: content of ref tag (if available)
760 importance: importance of place based on Wikipedia link count
761 addressimportance: cumulated importance of address elements
762 extra_place: type of place (for admin boundaries, if there is a place tag)
763 aBoundingBox: bounding Box
764 label: short description of the object class/type (English only)
765 name: full name (currently the same as langaddress)
766 foundorder: secondary ordering for places with same importance
770 if (!$this->sQuery && !$this->aStructuredQuery) return false;
772 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
773 $sCountryCodesSQL = false;
774 if ($this->aCountryCodes && sizeof($this->aCountryCodes))
776 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
779 $sQuery = $this->sQuery;
781 // Conflicts between US state abreviations and various words for 'the' in different languages
782 if (isset($this->aLangPrefOrder['name:en']))
784 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/','\1illinois\2', $sQuery);
785 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery);
786 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery);
790 $sViewboxCentreSQL = false;
791 $bBoundingBoxSearch = false;
794 $fHeight = $this->aViewBox[0]-$this->aViewBox[2];
795 $fWidth = $this->aViewBox[1]-$this->aViewBox[3];
796 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
797 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
798 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
799 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
801 $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)";
802 $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aBigViewBox[0].",".(float)$aBigViewBox[1]."),ST_Point(".(float)$aBigViewBox[2].",".(float)$aBigViewBox[3].")),4326)";
803 $bBoundingBoxSearch = $this->bBoundedSearch;
807 if ($this->aRoutePoints)
809 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
811 foreach($this->aRoutePoints as $aPoint)
813 if (!$bFirst) $sViewboxCentreSQL .= ",";
814 $sViewboxCentreSQL .= $aPoint[0].' '.$aPoint[1];
817 $sViewboxCentreSQL .= ")'::geometry,4326)";
819 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
820 $this->sViewboxSmallSQL = $this->oDB->getOne($sSQL);
821 if (PEAR::isError($this->sViewboxSmallSQL))
823 failInternalError("Could not get small viewbox.", $sSQL, $this->sViewboxSmallSQL);
825 $this->sViewboxSmallSQL = "'".$this->sViewboxSmallSQL."'::geometry";
827 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
828 $this->sViewboxLargeSQL = $this->oDB->getOne($sSQL);
829 if (PEAR::isError($this->sViewboxLargeSQL))
831 failInternalError("Could not get large viewbox.", $sSQL, $this->sViewboxLargeSQL);
833 $this->sViewboxLargeSQL = "'".$this->sViewboxLargeSQL."'::geometry";
834 $bBoundingBoxSearch = $this->bBoundedSearch;
837 // Do we have anything that looks like a lat/lon pair?
838 if ( $aLooksLike = looksLikeLatLonPair($sQuery) ){
839 $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
840 $sQuery = $aLooksLike['query'];
843 $aSearchResults = array();
844 if ($sQuery || $this->aStructuredQuery)
846 // Start with a blank search
848 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
849 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
850 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
853 // Do we have a radius search?
854 $sNearPointSQL = false;
855 if ($this->aNearPoint)
857 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
858 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
859 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
860 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
863 // Any 'special' terms in the search?
864 $bSpecialTerms = false;
865 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
866 $aSpecialTerms = array();
867 foreach($aSpecialTermsRaw as $aSpecialTerm)
869 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
870 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
873 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
874 $aSpecialTerms = array();
875 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity'])
877 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
878 unset($this->aStructuredQuery['amenity']);
880 foreach($aSpecialTermsRaw as $aSpecialTerm)
882 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
883 $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
884 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
885 $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';
886 if (CONST_Debug) var_Dump($sSQL);
887 $aSearchWords = $this->oDB->getAll($sSQL);
888 $aNewSearches = array();
889 foreach($aSearches as $aSearch)
891 foreach($aSearchWords as $aSearchTerm)
893 $aNewSearch = $aSearch;
894 if ($aSearchTerm['country_code'])
896 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
897 $aNewSearches[] = $aNewSearch;
898 $bSpecialTerms = true;
900 if ($aSearchTerm['class'])
902 $aNewSearch['sClass'] = $aSearchTerm['class'];
903 $aNewSearch['sType'] = $aSearchTerm['type'];
904 $aNewSearches[] = $aNewSearch;
905 $bSpecialTerms = true;
909 $aSearches = $aNewSearches;
912 // Split query into phrases
913 // Commas are used to reduce the search space by indicating where phrases split
914 if ($this->aStructuredQuery)
916 $aPhrases = $this->aStructuredQuery;
917 $bStructuredPhrases = true;
921 $aPhrases = explode(',',$sQuery);
922 $bStructuredPhrases = false;
925 // Convert each phrase to standard form
926 // Create a list of standard words
927 // Get all 'sets' of words
928 // Generate a complete list of all
930 foreach($aPhrases as $iPhrase => $sPhrase)
932 $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
933 if (PEAR::isError($aPhrase))
935 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
936 if (CONST_Debug) var_dump($aPhrase);
939 if (trim($aPhrase['string']))
941 $aPhrases[$iPhrase] = $aPhrase;
942 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
943 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
944 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
948 unset($aPhrases[$iPhrase]);
952 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
953 $aPhraseTypes = array_keys($aPhrases);
954 $aPhrases = array_values($aPhrases);
956 if (sizeof($aTokens))
958 // Check which tokens we have, get the ID numbers
959 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
960 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
962 if (CONST_Debug) var_Dump($sSQL);
964 $aValidTokens = array();
965 if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL);
966 else $aDatabaseWords = array();
967 if (PEAR::IsError($aDatabaseWords))
969 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
971 $aPossibleMainWordIDs = array();
972 $aWordFrequencyScores = array();
973 foreach($aDatabaseWords as $aToken)
975 // Very special case - require 2 letter country param to match the country code found
976 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
977 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code'])
982 if (isset($aValidTokens[$aToken['word_token']]))
984 $aValidTokens[$aToken['word_token']][] = $aToken;
988 $aValidTokens[$aToken['word_token']] = array($aToken);
990 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
991 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
993 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
995 // Try and calculate GB postcodes we might be missing
996 foreach($aTokens as $sToken)
998 // Source of gb postcodes is now definitive - always use
999 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
1001 if (substr($aData[1],-2,1) != ' ')
1003 $aData[0] = substr($aData[0],0,strlen($aData[1])-1).' '.substr($aData[0],strlen($aData[1])-1);
1004 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
1006 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1007 if ($aGBPostcodeLocation)
1009 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1012 // US ZIP+4 codes - if there is no token,
1013 // merge in the 5-digit ZIP code
1014 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
1016 if (isset($aValidTokens[$aData[1]]))
1018 foreach($aValidTokens[$aData[1]] as $aToken)
1020 if (!$aToken['class'])
1022 if (isset($aValidTokens[$sToken]))
1024 $aValidTokens[$sToken][] = $aToken;
1028 $aValidTokens[$sToken] = array($aToken);
1036 foreach($aTokens as $sToken)
1038 // Unknown single word token with a number - assume it is a house number
1039 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
1041 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
1045 // Any words that have failed completely?
1046 // TODO: suggestions
1048 // Start the search process
1049 $aResultPlaceIDs = array();
1051 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
1053 if ($this->bReverseInPlan)
1055 // Reverse phrase array and also reverse the order of the wordsets in
1056 // the first and final phrase. Don't bother about phrases in the middle
1057 // because order in the address doesn't matter.
1058 $aPhrases = array_reverse($aPhrases);
1059 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1060 if (sizeof($aPhrases) > 1)
1062 $aFinalPhrase = end($aPhrases);
1063 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1065 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1067 foreach($aGroupedSearches as $aSearches)
1069 foreach($aSearches as $aSearch)
1071 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1073 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1074 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1080 $aGroupedSearches = $aReverseGroupedSearches;
1081 ksort($aGroupedSearches);
1086 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1087 $aGroupedSearches = array();
1088 foreach($aSearches as $aSearch)
1090 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1092 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1093 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1096 ksort($aGroupedSearches);
1099 if (CONST_Debug) var_Dump($aGroupedSearches);
1101 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0)
1103 $aCopyGroupedSearches = $aGroupedSearches;
1104 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
1106 foreach($aSearches as $iSearch => $aSearch)
1108 $aReductionsList = array($aSearch['aAddress']);
1109 $iSearchRank = $aSearch['iSearchRank'];
1110 while(sizeof($aReductionsList) > 0)
1113 if ($iSearchRank > iMaxRank) break 3;
1114 $aNewReductionsList = array();
1115 foreach($aReductionsList as $aReductionsWordList)
1117 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
1119 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1120 $aReverseSearch = $aSearch;
1121 $aSearch['aAddress'] = $aReductionsWordListResult;
1122 $aSearch['iSearchRank'] = $iSearchRank;
1123 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1124 if (sizeof($aReductionsWordListResult) > 0)
1126 $aNewReductionsList[] = $aReductionsWordListResult;
1130 $aReductionsList = $aNewReductionsList;
1134 ksort($aGroupedSearches);
1137 // Filter out duplicate searches
1138 $aSearchHash = array();
1139 foreach($aGroupedSearches as $iGroup => $aSearches)
1141 foreach($aSearches as $iSearch => $aSearch)
1143 $sHash = serialize($aSearch);
1144 if (isset($aSearchHash[$sHash]))
1146 unset($aGroupedSearches[$iGroup][$iSearch]);
1147 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1151 $aSearchHash[$sHash] = 1;
1156 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1160 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
1163 foreach($aSearches as $aSearch)
1167 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
1168 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1170 // No location term?
1171 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
1173 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
1175 // Just looking for a country by code - look it up
1176 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
1178 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1179 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1180 if ($bBoundingBoxSearch)
1181 $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
1182 $sSQL .= " order by st_area(geometry) desc limit 1";
1183 if (CONST_Debug) var_dump($sSQL);
1184 $aPlaceIDs = $this->oDB->getCol($sSQL);
1188 $aPlaceIDs = array();
1193 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1194 if (!$aSearch['sClass']) continue;
1195 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1196 if ($this->oDB->getOne($sSQL))
1198 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1199 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1200 $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1201 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1202 if (sizeof($this->aExcludePlaceIDs))
1204 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1206 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1207 $sSQL .= " limit $this->iLimit";
1208 if (CONST_Debug) var_dump($sSQL);
1209 $aPlaceIDs = $this->oDB->getCol($sSQL);
1211 // If excluded place IDs are given, it is fair to assume that
1212 // there have been results in the small box, so no further
1213 // expansion in that case.
1214 // Also don't expand if bounded results were requested.
1215 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch)
1217 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1218 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1219 $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1220 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1221 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1222 $sSQL .= " limit $this->iLimit";
1223 if (CONST_Debug) var_dump($sSQL);
1224 $aPlaceIDs = $this->oDB->getCol($sSQL);
1229 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1230 $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1231 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1232 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
1233 $sSQL .= " limit $this->iLimit";
1234 if (CONST_Debug) var_dump($sSQL);
1235 $aPlaceIDs = $this->oDB->getCol($sSQL);
1241 $aPlaceIDs = array();
1243 // First we need a position, either aName or fLat or both
1247 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress']))
1249 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1250 $aOrder[] = "exists(select place_id from placex where parent_place_id = search_name.place_id and transliteration(housenumber) ~* E'".$sHouseNumberRegex."' limit 1) desc";
1253 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1254 // they might be right - but they are just too darned expensive to run
1255 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
1256 //if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
1257 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
1259 // For infrequent name terms disable index usage for address
1260 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
1261 sizeof($aSearch['aName']) == 1 &&
1262 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
1264 //$aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
1265 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
1269 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
1270 //if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
1273 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1274 if ($aSearch['sHouseNumber'])
1276 $aTerms[] = "address_rank between 16 and 27";
1280 if ($this->iMinAddressRank > 0)
1282 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1284 if ($this->iMaxAddressRank < 30)
1286 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1289 if ($aSearch['fLon'] && $aSearch['fLat'])
1291 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1292 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1294 if (sizeof($this->aExcludePlaceIDs))
1296 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1298 if ($sCountryCodesSQL)
1300 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1303 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1304 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1306 if ($aSearch['sHouseNumber'])
1308 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1312 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1314 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1315 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1317 $aOrder[] = "$sImportanceSQL DESC";
1318 if (sizeof($aSearch['aFullNameAddress']))
1320 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1321 $aOrder[] = 'exactmatch DESC';
1323 $sExactMatchSQL = '0::int as exactmatch';
1326 if (sizeof($aTerms))
1328 $sSQL = "select place_id, ";
1329 $sSQL .= $sExactMatchSQL;
1330 $sSQL .= " from search_name";
1331 $sSQL .= " where ".join(' and ',$aTerms);
1332 $sSQL .= " order by ".join(', ',$aOrder);
1333 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
1334 $sSQL .= " limit 20";
1335 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
1336 $sSQL .= " limit 1";
1338 $sSQL .= " limit ".$this->iLimit;
1340 if (CONST_Debug) { var_dump($sSQL); }
1341 $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL);
1342 if (PEAR::IsError($aViewBoxPlaceIDs))
1344 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
1346 //var_dump($aViewBoxPlaceIDs);
1347 // Did we have an viewbox matches?
1348 $aPlaceIDs = array();
1349 $bViewBoxMatch = false;
1350 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
1352 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1353 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1354 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1355 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1356 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1357 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1360 //var_Dump($aPlaceIDs);
1363 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1365 $aRoadPlaceIDs = $aPlaceIDs;
1366 $sPlaceIDs = join(',',$aPlaceIDs);
1368 // Now they are indexed look for a house attached to a street we found
1369 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1370 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1371 if (sizeof($this->aExcludePlaceIDs))
1373 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1375 $sSQL .= " limit $this->iLimit";
1376 if (CONST_Debug) var_dump($sSQL);
1377 $aPlaceIDs = $this->oDB->getCol($sSQL);
1379 // If not try the aux fallback table
1381 if (!sizeof($aPlaceIDs))
1383 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1384 if (sizeof($this->aExcludePlaceIDs))
1386 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1388 //$sSQL .= " limit $this->iLimit";
1389 if (CONST_Debug) var_dump($sSQL);
1390 $aPlaceIDs = $this->oDB->getCol($sSQL);
1394 if (!sizeof($aPlaceIDs))
1396 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1397 if (sizeof($this->aExcludePlaceIDs))
1399 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1401 //$sSQL .= " limit $this->iLimit";
1402 if (CONST_Debug) var_dump($sSQL);
1403 $aPlaceIDs = $this->oDB->getCol($sSQL);
1406 // Fallback to the road
1407 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1409 $aPlaceIDs = $aRoadPlaceIDs;
1414 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1416 $sPlaceIDs = join(',',$aPlaceIDs);
1417 $aClassPlaceIDs = array();
1419 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1421 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1422 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1423 $sSQL .= " and linked_place_id is null";
1424 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1425 $sSQL .= " order by rank_search asc limit $this->iLimit";
1426 if (CONST_Debug) var_dump($sSQL);
1427 $aClassPlaceIDs = $this->oDB->getCol($sSQL);
1430 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1432 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1433 $bCacheTable = $this->oDB->getOne($sSQL);
1435 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1437 if (CONST_Debug) var_dump($sSQL);
1438 $this->iMaxRank = ((int)$this->oDB->getOne($sSQL));
1440 // For state / country level searches the normal radius search doesn't work very well
1441 $sPlaceGeom = false;
1442 if ($this->iMaxRank < 9 && $bCacheTable)
1444 // Try and get a polygon to search in instead
1445 $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";
1446 if (CONST_Debug) var_dump($sSQL);
1447 $sPlaceGeom = $this->oDB->getOne($sSQL);
1456 $this->iMaxRank += 5;
1457 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1458 if (CONST_Debug) var_dump($sSQL);
1459 $aPlaceIDs = $this->oDB->getCol($sSQL);
1460 $sPlaceIDs = join(',',$aPlaceIDs);
1463 if ($sPlaceIDs || $sPlaceGeom)
1469 // More efficient - can make the range bigger
1473 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1474 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1475 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1477 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1478 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1481 $sSQL .= ",placex as f where ";
1482 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1487 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1489 if (sizeof($this->aExcludePlaceIDs))
1491 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1493 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1494 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1495 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1496 $sSQL .= " limit $this->iLimit";
1497 if (CONST_Debug) var_dump($sSQL);
1498 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1502 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1505 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1506 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1508 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1509 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1510 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1511 if (sizeof($this->aExcludePlaceIDs))
1513 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1515 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1516 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1517 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1518 $sSQL .= " limit $this->iLimit";
1519 if (CONST_Debug) var_dump($sSQL);
1520 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1525 $aPlaceIDs = $aClassPlaceIDs;
1531 if (PEAR::IsError($aPlaceIDs))
1533 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1536 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1538 foreach($aPlaceIDs as $iPlaceID)
1540 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1542 if ($iQueryLoop > 20) break;
1545 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
1547 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1548 $sSQL = "select place_id from placex where place_id in (".join(',',$aResultPlaceIDs).") ";
1549 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1550 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1551 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
1552 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',$aResultPlaceIDs).") ";
1553 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1554 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
1556 if (CONST_Debug) var_dump($sSQL);
1557 $aResultPlaceIDs = $this->oDB->getCol($sSQL);
1561 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1562 if ($iGroupLoop > 4) break;
1563 if ($iQueryLoop > 30) break;
1566 // Did we find anything?
1567 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1569 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1575 // Just interpret as a reverse geocode
1576 $iPlaceID = geocodeReverse((float)$this->aNearPoint[0], (float)$this->aNearPoint[1]);
1578 $aSearchResults = $this->getDetails(array($iPlaceID));
1580 $aSearchResults = array();
1584 if (!sizeof($aSearchResults))
1586 if ($this->bFallback)
1588 if ($this->fallbackStructuredQuery())
1590 return $this->lookup();
1597 $aClassType = getClassTypesWithImportance();
1598 $aRecheckWords = preg_split('/\b[\s,\\-]*/u',$sQuery);
1599 foreach($aRecheckWords as $i => $sWord)
1601 if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1604 if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
1606 foreach($aSearchResults as $iResNum => $aResult)
1609 $fDiameter = 0.0001;
1611 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1612 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1614 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
1616 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1617 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1619 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1621 $fRadius = $fDiameter / 2;
1623 if (CONST_Search_AreaPolygons)
1625 // Get the bounding box and outline polygon
1626 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1627 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1628 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
1629 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
1630 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1631 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1632 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1633 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
1634 $sFrom = " from placex where place_id = ".$aResult['place_id'];
1635 if ($this->fPolygonSimplificationThreshold > 0)
1637 $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
1644 $aPointPolygon = $this->oDB->getRow($sSQL);
1645 if (PEAR::IsError($aPointPolygon))
1647 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1650 if ($aPointPolygon['place_id'])
1652 if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1653 if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1654 if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1655 if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
1657 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1659 $aResult['lat'] = $aPointPolygon['centrelat'];
1660 $aResult['lon'] = $aPointPolygon['centrelon'];
1663 if ($this->bIncludePolygonAsPoints)
1665 // Translate geometry string to point array
1666 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1668 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1671 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1673 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1676 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1678 $iSteps = max(8, min(100, ($fRadius * 40000)^2));
1679 $fStepSize = (2*pi())/$iSteps;
1680 $aPolyPoints = array();
1681 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1683 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1688 // Output data suitable for display (points and a bounding box)
1689 if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
1691 $aResult['aPolyPoints'] = array();
1692 foreach($aPolyPoints as $aPoint)
1694 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1698 if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
1700 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1701 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1703 if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
1705 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1706 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1708 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1712 if ($aResult['extra_place'] == 'city')
1714 $aResult['class'] = 'place';
1715 $aResult['type'] = 'city';
1716 $aResult['rank_search'] = 16;
1719 if (!isset($aResult['aBoundingBox']))
1721 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1722 $fStepSize = (2*pi())/$iSteps;
1723 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1724 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1725 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1726 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1728 // Output data suitable for display (points and a bounding box)
1729 if ($this->bIncludePolygonAsPoints)
1731 $aPolyPoints = array();
1732 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1734 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1736 $aResult['aPolyPoints'] = array();
1737 foreach($aPolyPoints as $aPoint)
1739 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1742 $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
1745 // Is there an icon set for this type of result?
1746 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1747 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1749 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1752 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1753 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1755 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1757 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1758 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1760 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1763 if ($this->bIncludeAddressDetails)
1765 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1766 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1768 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1772 // Adjust importance for the number of exact string matches in the result
1773 $aResult['importance'] = max(0.001,$aResult['importance']);
1775 $sAddress = $aResult['langaddress'];
1776 foreach($aRecheckWords as $i => $sWord)
1778 if (stripos($sAddress, $sWord)!==false)
1781 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1785 $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
1787 $aResult['name'] = $aResult['langaddress'];
1788 // secondary ordering (for results with same importance (the smaller the better):
1789 // - approximate importance of address parts
1790 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1791 // - number of exact matches from the query
1792 if (isset($this->exactMatchCache[$aResult['place_id']]))
1793 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1794 else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
1795 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1796 // - importance of the class/type
1797 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1798 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1800 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1804 $aResult['foundorder'] += 0.01;
1806 $aSearchResults[$iResNum] = $aResult;
1808 uasort($aSearchResults, 'byImportance');
1810 $aOSMIDDone = array();
1811 $aClassTypeNameDone = array();
1812 $aToFilter = $aSearchResults;
1813 $aSearchResults = array();
1816 foreach($aToFilter as $iResNum => $aResult)
1818 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1821 $fLat = $aResult['lat'];
1822 $fLon = $aResult['lon'];
1823 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1826 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1827 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1829 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1830 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1831 $aSearchResults[] = $aResult;
1834 // Absolute limit on number of results
1835 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1838 return $aSearchResults;