2 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
3 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
9 protected $aLangPrefOrder = array();
11 protected $bIncludeAddressDetails = false;
12 protected $bIncludeExtraTags = false;
13 protected $bIncludeNameDetails = false;
15 protected $bIncludePolygonAsPoints = false;
16 protected $bIncludePolygonAsText = false;
17 protected $bIncludePolygonAsGeoJSON = false;
18 protected $bIncludePolygonAsKML = false;
19 protected $bIncludePolygonAsSVG = false;
20 protected $fPolygonSimplificationThreshold = 0.0;
22 protected $aExcludePlaceIDs = array();
23 protected $bDeDupe = true;
24 protected $bReverseInPlan = false;
26 protected $iLimit = 20;
27 protected $iFinalLimit = 10;
28 protected $iOffset = 0;
29 protected $bFallback = false;
31 protected $aCountryCodes = false;
32 protected $aNearPoint = false;
34 protected $bBoundedSearch = false;
35 protected $aViewBox = false;
36 protected $sViewboxCentreSQL = false;
37 protected $sViewboxSmallSQL = false;
38 protected $sViewboxLargeSQL = false;
40 protected $iMaxRank = 20;
41 protected $iMinAddressRank = 0;
42 protected $iMaxAddressRank = 30;
43 protected $aAddressRankList = array();
44 protected $exactMatchCache = array();
46 protected $sAllowedTypesSQLList = false;
48 protected $sQuery = false;
49 protected $aStructuredQuery = false;
51 function Geocode(&$oDB)
56 function setReverseInPlan($bReverse)
58 $this->bReverseInPlan = $bReverse;
61 function setLanguagePreference($aLangPref)
63 $this->aLangPrefOrder = $aLangPref;
66 function getIncludeAddressDetails()
68 return $this->bIncludeAddressDetails;
71 function getIncludeExtraTags()
73 return $this->bIncludeExtraTags;
76 function getIncludeNameDetails()
78 return $this->bIncludeNameDetails;
81 function setIncludePolygonAsPoints($b = true)
83 $this->bIncludePolygonAsPoints = $b;
86 function setIncludePolygonAsText($b = true)
88 $this->bIncludePolygonAsText = $b;
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 setLimit($iLimit = 10)
113 if ($iLimit > 50) $iLimit = 50;
114 if ($iLimit < 1) $iLimit = 1;
116 $this->iFinalLimit = $iLimit;
117 $this->iLimit = $iLimit + min($iLimit, 10);
120 function getExcludedPlaceIDs()
122 return $this->aExcludePlaceIDs;
125 function getViewBoxString()
127 if (!$this->aViewBox) return null;
128 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
131 function setFeatureType($sFeatureType)
133 switch($sFeatureType)
136 $this->setRankRange(4, 4);
139 $this->setRankRange(8, 8);
142 $this->setRankRange(14, 16);
145 $this->setRankRange(8, 20);
150 function setRankRange($iMin, $iMax)
152 $this->iMinAddressRank = $iMin;
153 $this->iMaxAddressRank = $iMax;
156 function setRoute($aRoutePoints, $fRouteWidth)
158 $this->aViewBox = false;
160 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
162 foreach($this->aRoutePoints as $aPoint)
164 $fPoint = (float)$aPoint;
165 $this->sViewboxCentreSQL .= $sSep.$fPoint;
166 $sSep = ($sSep == ' ') ? ',' : ' ';
168 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
170 $this->sViewboxSmallSQL = 'st_buffer('.$this->sViewboxCentreSQL;
171 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
173 $this->sViewboxLargeSQL = 'st_buffer('.$this->sViewboxCentreSQL;
174 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
177 function setViewbox($aViewbox)
179 $this->aViewBox = array_map('floatval', $aViewbox);
181 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
182 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
183 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
184 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
185 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
186 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
188 $this->sViewboxCentreSQL = false;
189 $this->sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".$this->aViewBox[0].",".$this->aViewBox[1]."),ST_Point(".$this->aViewBox[2].",".$this->aViewBox[3].")),4326)";
190 $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".$aBigViewBox[0].",".$aBigViewBox[1]."),ST_Point(".$aBigViewBox[2].",".$aBigViewBox[3].")),4326)";
193 function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
195 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
198 function setQuery($sQueryString)
200 $this->sQuery = $sQueryString;
201 $this->aStructuredQuery = false;
204 function getQueryString()
206 return $this->sQuery;
210 function loadParamArray($oParams)
212 $this->bIncludeAddressDetails = $oParams->getBool('addressdetails',
213 $this->bIncludeAddressDetails);
214 $this->bIncludeExtraTags = $oParams->getBool('extratags',
215 $this->bIncludeExtraTags);
216 $this->bIncludeNameDetails = $oParams->getBool('namedetails',
217 $this->bIncludeNameDetails);
219 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
220 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
222 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
223 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
225 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
227 // List of excluded Place IDs - used for more acurate pageing
228 $sExcluded = $oParams->getStringList('exclude_place_ids');
231 foreach($sExcluded as $iExcludedPlaceID)
233 $iExcludedPlaceID = (int)$iExcludedPlaceID;
234 if ($iExcludedPlaceID)
235 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
238 if (isset($aExcludePlaceIDs))
239 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
242 // Only certain ranks of feature
243 $sFeatureType = $oParams->getString('featureType');
244 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
245 if ($sFeatureType) $this->setFeatureType($sFeatureType);
248 $sCountries = $oParams->getStringList('countrycodes');
251 foreach($sCountries as $sCountryCode)
253 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
255 $aCountries[] = strtolower($sCountryCode);
258 if (isset($aCountryCodes))
259 $this->aCountryCodes = $aCountries;
262 $aViewbox = $oParams->getStringList('viewboxlbrt');
265 $this->setViewbox($aViewbox);
269 $aViewbox = $oParams->getStringList('viewbox');
272 $this->setViewBox(array($aViewbox[0], $aViewbox[3],
273 $aViewbox[2], $aViewbox[1]));
277 $aRoute = $oParams->getStringList('route');
278 $fRouteWidth = $oParams->getFloat('routewidth');
279 if ($aRoute && $fRouteWidth)
281 $this->setRoute($aRoute, $fRouteWidth);
287 function setQueryFromParams($oParams)
290 $sQuery = $oParams->getString('q');
293 $this->setStructuredQuery($oParams->getString('amenity'),
294 $oParams->getString('street'),
295 $oParams->getString('city'),
296 $oParams->getString('county'),
297 $oParams->getString('state'),
298 $oParams->getString('country'),
299 $oParams->getString('postalcode'));
300 $this->setReverseInPlan(false);
304 $this->setQuery($sQuery);
308 function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
310 $sValue = trim($sValue);
311 if (!$sValue) return false;
312 $this->aStructuredQuery[$sKey] = $sValue;
313 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30)
315 $this->iMinAddressRank = $iNewMinAddressRank;
316 $this->iMaxAddressRank = $iNewMaxAddressRank;
318 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
322 function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
324 $this->sQuery = false;
327 $this->iMinAddressRank = 0;
328 $this->iMaxAddressRank = 30;
329 $this->aAddressRankList = array();
331 $this->aStructuredQuery = array();
332 $this->sAllowedTypesSQLList = '';
334 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
335 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
336 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
337 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
338 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
339 $this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11));
340 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
342 if (sizeof($this->aStructuredQuery) > 0)
344 $this->sQuery = join(', ', $this->aStructuredQuery);
345 if ($this->iMaxAddressRank < 30)
347 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
352 function fallbackStructuredQuery()
354 if (!$this->aStructuredQuery) return false;
356 $aParams = $this->aStructuredQuery;
358 if (sizeof($aParams) == 1) return false;
360 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
362 foreach($aOrderToFallback as $sType)
364 if (isset($aParams[$sType]))
366 unset($aParams[$sType]);
367 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
375 function getDetails($aPlaceIDs)
377 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
378 if (sizeof($aPlaceIDs) == 0) return array();
380 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
382 // Get the details for display (is this a redundant extra step?)
383 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
385 $sImportanceSQL = '';
386 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
387 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
389 $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,";
390 $sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
391 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
392 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
393 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text as extra,";
394 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text as names,";
395 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
396 $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
397 $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, ";
398 $sSQL .= "(extratags->'place') as extra_place ";
399 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
400 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
401 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
402 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
404 if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
405 $sSQL .= "and linked_place_id is null ";
406 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
407 if (!$this->bDeDupe) $sSQL .= ",place_id";
408 $sSQL .= ",langaddress ";
409 $sSQL .= ",placename ";
411 if ($this->bIncludeExtraTags) $sSQL .= ",extratags";
412 if ($this->bIncludeNameDetails) $sSQL .= ",name";
413 $sSQL .= ",extratags->'place' ";
415 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
417 //only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
418 // with start- and endnumber, the common osm housenumbers are usually saved as points
421 $length = count($aPlaceIDs);
422 foreach($aPlaceIDs as $placeID => $housenumber)
425 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
427 $sHousenumbers .= ", ";
429 if (CONST_Use_US_Tiger_Data)
431 //Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
433 $sSQL .= " select 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code";
434 $sSQL .= ", get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress ";
435 $sSQL .= ", null as placename";
436 $sSQL .= ", null as ref";
437 if ($this->bIncludeExtraTags) $sSQL .= ", null as extra";
438 if ($this->bIncludeNameDetails) $sSQL .= ", null as names";
439 $sSQL .= ", avg(st_x(centroid)) as lon, avg(st_y(centroid)) as lat,";
440 $sSQL .= $sImportanceSQL."-1.15 as importance ";
441 $sSQL .= ", (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance ";
442 $sSQL .= ", null as extra_place ";
443 $sSQL .= " from (select place_id";
444 //interpolate the Tiger housenumbers here
445 $sSQL .= ", ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) as centroid, parent_place_id, housenumber_for_place";
446 $sSQL .= " from (location_property_tiger ";
447 $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
448 $sSQL .= " where housenumber_for_place>=0 and 30 between $this->iMinAddressRank and $this->iMaxAddressRank) as blub"; //postgres wants an alias here
449 $sSQL .= " group by place_id, housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
450 if (!$this->bDeDupe) $sSQL .= ", place_id ";
453 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
455 $sSQL .= "select 'W' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, calculated_country_code as country_code, ";
456 $sSQL .= "get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress, ";
457 $sSQL .= "null as placename, ";
458 $sSQL .= "null as ref, ";
459 if ($this->bIncludeExtraTags) $sSQL .= "null as extra, ";
460 if ($this->bIncludeNameDetails) $sSQL .= "null as names, ";
461 $sSQL .= " avg(st_x(centroid)) as lon, avg(st_y(centroid)) as lat,";
462 $sSQL .= $sImportanceSQL."-0.1 as importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
463 $sSQL .= " (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p";
464 $sSQL .= " where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance,";
465 $sSQL .= " null as extra_place ";
466 $sSQL .= " from (select place_id, calculated_country_code ";
467 //interpolate the housenumbers here
468 $sSQL .= ", CASE WHEN startnumber != endnumber THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
469 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) END as centroid";
470 $sSQL .= ", parent_place_id, housenumber_for_place ";
471 $sSQL .= " from (location_property_osmline ";
472 $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
473 $sSQL .= " where housenumber_for_place>=0 and 30 between $this->iMinAddressRank and $this->iMaxAddressRank) as blub"; //postgres wants an alias here
474 $sSQL .= " group by place_id, housenumber_for_place, calculated_country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
475 if (!$this->bDeDupe) $sSQL .= ", place_id ";
477 if (CONST_Use_Aux_Location_data)
480 $sSQL .= "select 'L' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 0 as rank_search, 0 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code, ";
481 $sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress, ";
482 $sSQL .= "null as placename, ";
483 $sSQL .= "null as ref, ";
484 if ($this->bIncludeExtraTags) $sSQL .= "null as extra, ";
485 if ($this->bIncludeNameDetails) $sSQL .= "null as names, ";
486 $sSQL .= "avg(ST_X(centroid)) as lon, avg(ST_Y(centroid)) as lat, ";
487 $sSQL .= $sImportanceSQL."-1.10 as importance, ";
488 $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, ";
489 $sSQL .= "null as extra_place ";
490 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
491 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
492 $sSQL .= "group by place_id";
493 if (!$this->bDeDupe) $sSQL .= ", place_id";
494 $sSQL .= ", get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
498 $sSQL .= " order by importance desc";
499 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
500 $aSearchResults = chksql($this->oDB->getAll($sSQL),
501 "Could not get details for place.");
503 return $aSearchResults;
506 function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
509 Calculate all searches using aValidTokens i.e.
510 'Wodsworth Road, Sheffield' =>
514 0 1 (wodsworth)(road)
517 Score how good the search is so they can be ordered
519 foreach($aPhrases as $iPhrase => $sPhrase)
521 $aNewPhraseSearches = array();
522 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
523 else $sPhraseType = '';
525 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
527 // Too many permutations - too expensive
528 if ($iWordSet > 120) break;
530 $aWordsetSearches = $aSearches;
532 // Add all words from this wordset
533 foreach($aWordset as $iToken => $sToken)
535 //echo "<br><b>$sToken</b>";
536 $aNewWordsetSearches = array();
538 foreach($aWordsetSearches as $aCurrentSearch)
541 //var_dump($aCurrentSearch);
544 // If the token is valid
545 if (isset($aValidTokens[' '.$sToken]))
547 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
549 $aSearch = $aCurrentSearch;
550 $aSearch['iSearchRank']++;
551 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
553 if ($aSearch['sCountryCode'] === false)
555 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
556 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
557 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)))
559 $aSearch['iSearchRank'] += 5;
561 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
564 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
566 if ($aSearch['fLat'] === '')
568 $aSearch['fLat'] = $aSearchTerm['lat'];
569 $aSearch['fLon'] = $aSearchTerm['lon'];
570 $aSearch['fRadius'] = $aSearchTerm['radius'];
571 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
574 elseif ($sPhraseType == 'postalcode')
576 // 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
577 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
579 // If we already have a name try putting the postcode first
580 if (sizeof($aSearch['aName']))
582 $aNewSearch = $aSearch;
583 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
584 $aNewSearch['aName'] = array();
585 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
586 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
589 if (sizeof($aSearch['aName']))
591 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
593 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
597 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
598 $aSearch['iSearchRank'] += 1000; // skip;
603 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
604 //$aSearch['iNamePhrase'] = $iPhrase;
606 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
610 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
612 if ($aSearch['sHouseNumber'] === '')
614 $aSearch['sHouseNumber'] = $sToken;
615 // sanity check: if the housenumber is not mainly made
616 // up of numbers, add a penalty
617 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
618 // also housenumbers should appear in the first or second phrase
619 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
620 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
622 // Fall back to not searching for this item (better than nothing)
623 $aSearch = $aCurrentSearch;
624 $aSearch['iSearchRank'] += 1;
625 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
629 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
631 if ($aSearch['sClass'] === '')
633 $aSearch['sOperator'] = $aSearchTerm['operator'];
634 $aSearch['sClass'] = $aSearchTerm['class'];
635 $aSearch['sType'] = $aSearchTerm['type'];
636 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
637 else $aSearch['sOperator'] = 'near'; // near = in for the moment
638 if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
640 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
643 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
645 if (sizeof($aSearch['aName']))
647 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
649 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
653 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
654 $aSearch['iSearchRank'] += 1000; // skip;
659 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
660 //$aSearch['iNamePhrase'] = $iPhrase;
662 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
666 // Look for partial matches.
667 // Note that there is no point in adding country terms here
668 // because country are omitted in the address.
669 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country')
671 // Allow searching for a word - but at extra cost
672 foreach($aValidTokens[$sToken] as $aSearchTerm)
674 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
676 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false)
678 $aSearch = $aCurrentSearch;
679 $aSearch['iSearchRank'] += 1;
680 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
682 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
683 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
685 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
687 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
688 $aSearch['iSearchRank'] += 1;
689 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
690 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
692 if (empty($aSearchTermToken['country_code'])
693 && empty($aSearchTermToken['lat'])
694 && empty($aSearchTermToken['class']))
696 $aSearch = $aCurrentSearch;
697 $aSearch['iSearchRank'] += 1;
698 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
699 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
705 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
706 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
707 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
711 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
713 $aSearch = $aCurrentSearch;
714 $aSearch['iSearchRank'] += 1;
715 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
716 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
717 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
718 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
720 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
721 $aSearch['iNamePhrase'] = $iPhrase;
722 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
729 // Allow skipping a word - but at EXTREAM cost
730 //$aSearch = $aCurrentSearch;
731 //$aSearch['iSearchRank']+=100;
732 //$aNewWordsetSearches[] = $aSearch;
736 usort($aNewWordsetSearches, 'bySearchRank');
737 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
739 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
741 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
742 usort($aNewPhraseSearches, 'bySearchRank');
744 $aSearchHash = array();
745 foreach($aNewPhraseSearches as $iSearch => $aSearch)
747 $sHash = serialize($aSearch);
748 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
749 else $aSearchHash[$sHash] = 1;
752 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
755 // Re-group the searches by their score, junk anything over 20 as just not worth trying
756 $aGroupedSearches = array();
757 foreach($aNewPhraseSearches as $aSearch)
759 if ($aSearch['iSearchRank'] < $this->iMaxRank)
761 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
762 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
765 ksort($aGroupedSearches);
768 $aSearches = array();
769 foreach($aGroupedSearches as $iScore => $aNewSearches)
771 $iSearchCount += sizeof($aNewSearches);
772 $aSearches = array_merge($aSearches, $aNewSearches);
773 if ($iSearchCount > 50) break;
776 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
779 return $aGroupedSearches;
783 /* Perform the actual query lookup.
785 Returns an ordered list of results, each with the following fields:
786 osm_type: type of corresponding OSM object
790 P - postcode (internally computed)
791 osm_id: id of corresponding OSM object
792 class: general object class (corresponds to tag key of primary OSM tag)
793 type: subclass of object (corresponds to tag value of primary OSM tag)
794 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
795 rank_search: rank in search hierarchy
796 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
797 rank_address: rank in address hierarchy (determines orer in address)
798 place_id: internal key (may differ between different instances)
799 country_code: ISO country code
800 langaddress: localized full address
801 placename: localized name of object
802 ref: content of ref tag (if available)
805 importance: importance of place based on Wikipedia link count
806 addressimportance: cumulated importance of address elements
807 extra_place: type of place (for admin boundaries, if there is a place tag)
808 aBoundingBox: bounding Box
809 label: short description of the object class/type (English only)
810 name: full name (currently the same as langaddress)
811 foundorder: secondary ordering for places with same importance
815 if (!$this->sQuery && !$this->aStructuredQuery) return false;
817 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
818 $sCountryCodesSQL = false;
819 if ($this->aCountryCodes)
821 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
824 $sQuery = $this->sQuery;
826 // Conflicts between US state abreviations and various words for 'the' in different languages
827 if (isset($this->aLangPrefOrder['name:en']))
829 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/','\1illinois\2', $sQuery);
830 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery);
831 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery);
834 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
835 if ($this->sViewboxCentreSQL)
837 // For complex viewboxes (routes) precompute the bounding geometry
838 $sGeom = chksql($this->oDB->getOne("select ".$this->sViewboxSmallSQL),
839 "Could not get small viewbox");
840 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
842 $sGeom = chksql($this->oDB->getOne("select ".$this->sViewboxLargeSQL),
843 "Could not get large viewbox");
844 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
847 // Do we have anything that looks like a lat/lon pair?
848 if ( $aLooksLike = looksLikeLatLonPair($sQuery) )
850 $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
851 $sQuery = $aLooksLike['query'];
854 $aSearchResults = array();
855 if ($sQuery || $this->aStructuredQuery)
857 // Start with a blank search
859 array('iSearchRank' => 0,
861 'sCountryCode' => false,
863 'aAddress' => array(),
864 'aFullNameAddress' => array(),
865 'aNameNonSearch' => array(),
866 'aAddressNonSearch' => array(),
868 'aFeatureName' => array(),
871 'sHouseNumber' => '',
878 // Do we have a radius search?
879 $sNearPointSQL = false;
880 if ($this->aNearPoint)
882 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
883 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
884 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
885 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
888 // Any 'special' terms in the search?
889 $bSpecialTerms = false;
890 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
891 $aSpecialTerms = array();
892 foreach($aSpecialTermsRaw as $aSpecialTerm)
894 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
895 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
898 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
899 $aSpecialTerms = array();
900 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity'])
902 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
903 unset($this->aStructuredQuery['amenity']);
905 foreach($aSpecialTermsRaw as $aSpecialTerm)
907 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
908 $sToken = chksql($this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string"));
909 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
910 $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';
911 if (CONST_Debug) var_Dump($sSQL);
912 $aSearchWords = chksql($this->oDB->getAll($sSQL));
913 $aNewSearches = array();
914 foreach($aSearches as $aSearch)
916 foreach($aSearchWords as $aSearchTerm)
918 $aNewSearch = $aSearch;
919 if ($aSearchTerm['country_code'])
921 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
922 $aNewSearches[] = $aNewSearch;
923 $bSpecialTerms = true;
925 if ($aSearchTerm['class'])
927 $aNewSearch['sClass'] = $aSearchTerm['class'];
928 $aNewSearch['sType'] = $aSearchTerm['type'];
929 $aNewSearches[] = $aNewSearch;
930 $bSpecialTerms = true;
934 $aSearches = $aNewSearches;
937 // Split query into phrases
938 // Commas are used to reduce the search space by indicating where phrases split
939 if ($this->aStructuredQuery)
941 $aPhrases = $this->aStructuredQuery;
942 $bStructuredPhrases = true;
946 $aPhrases = explode(',',$sQuery);
947 $bStructuredPhrases = false;
950 // Convert each phrase to standard form
951 // Create a list of standard words
952 // Get all 'sets' of words
953 // Generate a complete list of all
955 foreach($aPhrases as $iPhrase => $sPhrase)
957 $aPhrase = chksql($this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string"),
958 "Cannot nomralize query string (is it an UTF-8 string?)");
959 if (trim($aPhrase['string']))
961 $aPhrases[$iPhrase] = $aPhrase;
962 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
963 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
964 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
968 unset($aPhrases[$iPhrase]);
972 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
973 $aPhraseTypes = array_keys($aPhrases);
974 $aPhrases = array_values($aPhrases);
976 if (sizeof($aTokens))
978 // Check which tokens we have, get the ID numbers
979 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
980 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
982 if (CONST_Debug) var_Dump($sSQL);
984 $aValidTokens = array();
985 if (sizeof($aTokens))
987 $aDatabaseWords = chksql($this->oDB->getAll($sSQL),
988 "Could not get word tokens.");
992 $aDatabaseWords = array();
994 $aPossibleMainWordIDs = array();
995 $aWordFrequencyScores = array();
996 foreach($aDatabaseWords as $aToken)
998 // Very special case - require 2 letter country param to match the country code found
999 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1000 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code'])
1005 if (isset($aValidTokens[$aToken['word_token']]))
1007 $aValidTokens[$aToken['word_token']][] = $aToken;
1011 $aValidTokens[$aToken['word_token']] = array($aToken);
1013 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1014 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1016 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1018 // Try and calculate GB postcodes we might be missing
1019 foreach($aTokens as $sToken)
1021 // Source of gb postcodes is now definitive - always use
1022 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
1024 if (substr($aData[1],-2,1) != ' ')
1026 $aData[0] = substr($aData[0],0,strlen($aData[1])-1).' '.substr($aData[0],strlen($aData[1])-1);
1027 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
1029 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1030 if ($aGBPostcodeLocation)
1032 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1035 // US ZIP+4 codes - if there is no token,
1036 // merge in the 5-digit ZIP code
1037 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
1039 if (isset($aValidTokens[$aData[1]]))
1041 foreach($aValidTokens[$aData[1]] as $aToken)
1043 if (!$aToken['class'])
1045 if (isset($aValidTokens[$sToken]))
1047 $aValidTokens[$sToken][] = $aToken;
1051 $aValidTokens[$sToken] = array($aToken);
1059 foreach($aTokens as $sToken)
1061 // Unknown single word token with a number - assume it is a house number
1062 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
1064 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
1068 // Any words that have failed completely?
1069 // TODO: suggestions
1071 // Start the search process
1072 // array with: placeid => -1 | tiger-housenumber
1073 $aResultPlaceIDs = array();
1075 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
1077 if ($this->bReverseInPlan)
1079 // Reverse phrase array and also reverse the order of the wordsets in
1080 // the first and final phrase. Don't bother about phrases in the middle
1081 // because order in the address doesn't matter.
1082 $aPhrases = array_reverse($aPhrases);
1083 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1084 if (sizeof($aPhrases) > 1)
1086 $aFinalPhrase = end($aPhrases);
1087 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1089 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1091 foreach($aGroupedSearches as $aSearches)
1093 foreach($aSearches as $aSearch)
1095 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1097 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1098 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1104 $aGroupedSearches = $aReverseGroupedSearches;
1105 ksort($aGroupedSearches);
1110 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1111 $aGroupedSearches = array();
1112 foreach($aSearches as $aSearch)
1114 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1116 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1117 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1120 ksort($aGroupedSearches);
1123 if (CONST_Debug) var_Dump($aGroupedSearches);
1125 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0)
1127 $aCopyGroupedSearches = $aGroupedSearches;
1128 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
1130 foreach($aSearches as $iSearch => $aSearch)
1132 $aReductionsList = array($aSearch['aAddress']);
1133 $iSearchRank = $aSearch['iSearchRank'];
1134 while(sizeof($aReductionsList) > 0)
1137 if ($iSearchRank > iMaxRank) break 3;
1138 $aNewReductionsList = array();
1139 foreach($aReductionsList as $aReductionsWordList)
1141 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
1143 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1144 $aReverseSearch = $aSearch;
1145 $aSearch['aAddress'] = $aReductionsWordListResult;
1146 $aSearch['iSearchRank'] = $iSearchRank;
1147 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1148 if (sizeof($aReductionsWordListResult) > 0)
1150 $aNewReductionsList[] = $aReductionsWordListResult;
1154 $aReductionsList = $aNewReductionsList;
1158 ksort($aGroupedSearches);
1161 // Filter out duplicate searches
1162 $aSearchHash = array();
1163 foreach($aGroupedSearches as $iGroup => $aSearches)
1165 foreach($aSearches as $iSearch => $aSearch)
1167 $sHash = serialize($aSearch);
1168 if (isset($aSearchHash[$sHash]))
1170 unset($aGroupedSearches[$iGroup][$iSearch]);
1171 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1175 $aSearchHash[$sHash] = 1;
1180 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1184 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
1187 foreach($aSearches as $aSearch)
1190 $searchedHousenumber = -1;
1192 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
1193 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1195 // No location term?
1196 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
1198 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
1200 // Just looking for a country by code - look it up
1201 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
1203 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1204 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1205 if ($bBoundingBoxSearch)
1206 $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
1207 $sSQL .= " order by st_area(geometry) desc limit 1";
1208 if (CONST_Debug) var_dump($sSQL);
1209 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1213 $aPlaceIDs = array();
1218 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1219 if (!$aSearch['sClass']) continue;
1220 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1221 if (chksql($this->oDB->getOne($sSQL)))
1223 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1224 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1225 $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1226 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1227 if (sizeof($this->aExcludePlaceIDs))
1229 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1231 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1232 $sSQL .= " limit $this->iLimit";
1233 if (CONST_Debug) var_dump($sSQL);
1234 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1236 // If excluded place IDs are given, it is fair to assume that
1237 // there have been results in the small box, so no further
1238 // expansion in that case.
1239 // Also don't expand if bounded results were requested.
1240 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch)
1242 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1243 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1244 $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1245 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1246 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1247 $sSQL .= " limit $this->iLimit";
1248 if (CONST_Debug) var_dump($sSQL);
1249 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1254 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1255 $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1256 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1257 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, centroid) asc";
1258 $sSQL .= " limit $this->iLimit";
1259 if (CONST_Debug) var_dump($sSQL);
1260 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1264 // If a coordinate is given, the search must either
1265 // be for a name or a special search. Ignore everythin else.
1266 else if ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass'])
1268 $aPlaceIDs = array();
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';
1282 $aOrder[0] = " (exists(select place_id from placex where parent_place_id = search_name.place_id";
1283 $aOrder[0] .= " and transliteration(housenumber) ~* E'".$sHouseNumberRegex."' limit 1) ";
1284 // also housenumbers from interpolation lines table are needed
1285 $aOrder[0] .= " or exists(select place_id from location_property_osmline where parent_place_id = search_name.place_id";
1286 $aOrder[0] .= " and ".intval($aSearch['sHouseNumber']).">=startnumber and ".intval($aSearch['sHouseNumber'])."<=endnumber limit 1))";
1287 $aOrder[0] .= " desc";
1290 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1291 // they might be right - but they are just too darned expensive to run
1292 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
1293 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
1294 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
1296 // For infrequent name terms disable index usage for address
1297 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
1298 sizeof($aSearch['aName']) == 1 &&
1299 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
1301 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
1305 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
1306 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
1309 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1310 if ($aSearch['sHouseNumber'])
1312 $aTerms[] = "address_rank between 16 and 27";
1316 if ($this->iMinAddressRank > 0)
1318 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1320 if ($this->iMaxAddressRank < 30)
1322 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1325 if ($aSearch['fLon'] && $aSearch['fLat'])
1327 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1328 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1330 if (sizeof($this->aExcludePlaceIDs))
1332 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1334 if ($sCountryCodesSQL)
1336 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1339 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1340 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1342 if ($aSearch['sHouseNumber'])
1344 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1348 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1350 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1351 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1353 $aOrder[] = "$sImportanceSQL DESC";
1354 if (sizeof($aSearch['aFullNameAddress']))
1356 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1357 $aOrder[] = 'exactmatch DESC';
1359 $sExactMatchSQL = '0::int as exactmatch';
1362 if (sizeof($aTerms))
1364 $sSQL = "select place_id, ";
1365 $sSQL .= $sExactMatchSQL;
1366 $sSQL .= " from search_name";
1367 $sSQL .= " where ".join(' and ',$aTerms);
1368 $sSQL .= " order by ".join(', ',$aOrder);
1369 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
1370 $sSQL .= " limit 20";
1371 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
1372 $sSQL .= " limit 1";
1374 $sSQL .= " limit ".$this->iLimit;
1376 if (CONST_Debug) { var_dump($sSQL); }
1377 $aViewBoxPlaceIDs = chksql($this->oDB->getAll($sSQL),
1378 "Could not get places for search terms.");
1379 //var_dump($aViewBoxPlaceIDs);
1380 // Did we have an viewbox matches?
1381 $aPlaceIDs = array();
1382 $bViewBoxMatch = false;
1383 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
1385 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1386 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1387 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1388 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1389 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1390 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1393 //var_Dump($aPlaceIDs);
1396 //now search for housenumber, if housenumber provided
1397 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1399 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1400 $aRoadPlaceIDs = $aPlaceIDs;
1401 $sPlaceIDs = join(',',$aPlaceIDs);
1403 // Now they are indexed, look for a house attached to a street we found
1404 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1405 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1406 if (sizeof($this->aExcludePlaceIDs))
1408 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1410 $sSQL .= " limit $this->iLimit";
1411 if (CONST_Debug) var_dump($sSQL);
1412 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1414 // if nothing found, search in the interpolation line table
1415 if(!sizeof($aPlaceIDs))
1417 // do we need to use transliteration and the regex for housenumbers???
1418 //new query for lines, not housenumbers anymore
1419 if($searchedHousenumber%2 == 0){
1420 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1421 $sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1423 //look for housenumber in streets with interpolationtype odd or all
1424 $sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1427 if (sizeof($this->aExcludePlaceIDs))
1429 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1431 //$sSQL .= " limit $this->iLimit";
1432 if (CONST_Debug) var_dump($sSQL);
1434 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1437 // If nothing found try the aux fallback table
1438 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs))
1440 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1441 if (sizeof($this->aExcludePlaceIDs))
1443 $sSQL .= " and parent_place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1445 //$sSQL .= " limit $this->iLimit";
1446 if (CONST_Debug) var_dump($sSQL);
1447 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1450 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1451 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs))
1453 //new query for lines, not housenumbers anymore
1454 if($searchedHousenumber%2 == 0){
1455 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1456 $sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1458 //look for housenumber in streets with interpolationtype odd or all
1459 $sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1462 if (sizeof($this->aExcludePlaceIDs))
1464 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1466 //$sSQL .= " limit $this->iLimit";
1467 if (CONST_Debug) var_dump($sSQL);
1469 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1472 // Fallback to the road (if no housenumber was found)
1473 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1475 $aPlaceIDs = $aRoadPlaceIDs;
1476 //set to -1, if no housenumbers were found
1477 $searchedHousenumber = -1;
1479 //else: housenumber was found, remains saved in searchedHousenumber
1483 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1485 $sPlaceIDs = join(',', $aPlaceIDs);
1486 $aClassPlaceIDs = array();
1488 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1490 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1491 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1492 $sSQL .= " and linked_place_id is null";
1493 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1494 $sSQL .= " order by rank_search asc limit $this->iLimit";
1495 if (CONST_Debug) var_dump($sSQL);
1496 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1499 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1501 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1502 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1504 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1506 if (CONST_Debug) var_dump($sSQL);
1507 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1509 // For state / country level searches the normal radius search doesn't work very well
1510 $sPlaceGeom = false;
1511 if ($this->iMaxRank < 9 && $bCacheTable)
1513 // Try and get a polygon to search in instead
1514 $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";
1515 if (CONST_Debug) var_dump($sSQL);
1516 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1525 $this->iMaxRank += 5;
1526 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1527 if (CONST_Debug) var_dump($sSQL);
1528 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1529 $sPlaceIDs = join(',',$aPlaceIDs);
1532 if ($sPlaceIDs || $sPlaceGeom)
1538 // More efficient - can make the range bigger
1542 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1543 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1544 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1546 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1547 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1550 $sSQL .= ",placex as f where ";
1551 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1556 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1558 if (sizeof($this->aExcludePlaceIDs))
1560 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1562 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1563 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1564 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1565 $sSQL .= " limit $this->iLimit";
1566 if (CONST_Debug) var_dump($sSQL);
1567 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1571 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1574 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1575 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1577 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1578 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1579 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1580 if (sizeof($this->aExcludePlaceIDs))
1582 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1584 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1585 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1586 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1587 $sSQL .= " limit $this->iLimit";
1588 if (CONST_Debug) var_dump($sSQL);
1589 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1594 $aPlaceIDs = $aClassPlaceIDs;
1600 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1602 foreach($aPlaceIDs as $iPlaceID)
1604 // array for placeID => -1 | Tiger housenumber
1605 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1607 if ($iQueryLoop > 20) break;
1610 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
1612 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1613 // reduces the number of place ids, like a filter
1614 // rank_address is 30 for interpolated housenumbers
1615 $sSQL = "select place_id from placex where place_id in (".join(',',array_keys($aResultPlaceIDs)).") ";
1616 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1617 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1618 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
1619 if (CONST_Use_US_Tiger_Data)
1621 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',array_keys($aResultPlaceIDs)).") ";
1622 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1623 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
1625 $sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',',array_keys($aResultPlaceIDs)).")";
1626 $sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1627 if (CONST_Debug) var_dump($sSQL);
1628 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1630 foreach($aFilteredPlaceIDs as $placeID)
1632 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1634 $aResultPlaceIDs = $tempIDs;
1638 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1639 if ($iGroupLoop > 4) break;
1640 if ($iQueryLoop > 30) break;
1643 // Did we find anything?
1644 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1646 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1652 // Just interpret as a reverse geocode
1653 $oReverse = new ReverseGeocode($this->oDB);
1654 $oReverse->setZoom(18);
1656 $aLookup = $oReverse->lookup((float)$this->aNearPoint[0],
1657 (float)$this->aNearPoint[1],
1660 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1662 if ($aLookup['place_id'])
1663 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1665 $aSearchResults = array();
1669 if (!sizeof($aSearchResults))
1671 if ($this->bFallback)
1673 if ($this->fallbackStructuredQuery())
1675 return $this->lookup();
1682 $aClassType = getClassTypesWithImportance();
1683 $aRecheckWords = preg_split('/\b[\s,\\-]*/u',$sQuery);
1684 foreach($aRecheckWords as $i => $sWord)
1686 if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1689 if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
1691 $oPlaceLookup = new PlaceLookup($this->oDB);
1692 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1693 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1694 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1695 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1696 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1697 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1699 foreach($aSearchResults as $iResNum => $aResult)
1702 $fDiameter = getResultDiameter($aResult);
1704 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1705 if ($aOutlineResult)
1707 $aResult = array_merge($aResult, $aOutlineResult);
1710 if ($aResult['extra_place'] == 'city')
1712 $aResult['class'] = 'place';
1713 $aResult['type'] = 'city';
1714 $aResult['rank_search'] = 16;
1717 // Is there an icon set for this type of result?
1718 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1719 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1721 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1724 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1725 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1727 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1729 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1730 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1732 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1734 // if tag '&addressdetails=1' is set in query
1735 if ($this->bIncludeAddressDetails)
1737 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1738 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1739 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1741 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1744 if ($this->bIncludeExtraTags)
1746 if ($aResult['extra'])
1748 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1752 $aResult['sExtraTags'] = (object) array();
1756 if ($this->bIncludeNameDetails)
1758 if ($aResult['names'])
1760 $aResult['sNameDetails'] = json_decode($aResult['names']);
1764 $aResult['sNameDetails'] = (object) array();
1768 // Adjust importance for the number of exact string matches in the result
1769 $aResult['importance'] = max(0.001,$aResult['importance']);
1771 $sAddress = $aResult['langaddress'];
1772 foreach($aRecheckWords as $i => $sWord)
1774 if (stripos($sAddress, $sWord)!==false)
1777 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1781 $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
1783 $aResult['name'] = $aResult['langaddress'];
1784 // secondary ordering (for results with same importance (the smaller the better):
1785 // - approximate importance of address parts
1786 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1787 // - number of exact matches from the query
1788 if (isset($this->exactMatchCache[$aResult['place_id']]))
1789 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1790 else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
1791 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1792 // - importance of the class/type
1793 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1794 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1796 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1800 $aResult['foundorder'] += 0.01;
1802 if (CONST_Debug) { var_dump($aResult); }
1803 $aSearchResults[$iResNum] = $aResult;
1805 uasort($aSearchResults, 'byImportance');
1807 $aOSMIDDone = array();
1808 $aClassTypeNameDone = array();
1809 $aToFilter = $aSearchResults;
1810 $aSearchResults = array();
1813 foreach($aToFilter as $iResNum => $aResult)
1815 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1818 $fLat = $aResult['lat'];
1819 $fLon = $aResult['lon'];
1820 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1823 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1824 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1826 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1827 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1828 $aSearchResults[] = $aResult;
1831 // Absolute limit on number of results
1832 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1835 return $aSearchResults;