5 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
6 require_once(CONST_BasePath.'/lib/Phrase.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
8 require_once(CONST_BasePath.'/lib/SearchDescription.php');
9 require_once(CONST_BasePath.'/lib/SearchContext.php');
15 protected $aLangPrefOrder = array();
17 protected $bIncludeAddressDetails = false;
18 protected $bIncludeExtraTags = false;
19 protected $bIncludeNameDetails = false;
21 protected $bIncludePolygonAsPoints = false;
22 protected $bIncludePolygonAsText = false;
23 protected $bIncludePolygonAsGeoJSON = false;
24 protected $bIncludePolygonAsKML = false;
25 protected $bIncludePolygonAsSVG = false;
26 protected $fPolygonSimplificationThreshold = 0.0;
28 protected $aExcludePlaceIDs = array();
29 protected $bDeDupe = true;
30 protected $bReverseInPlan = false;
32 protected $iLimit = 20;
33 protected $iFinalLimit = 10;
34 protected $iOffset = 0;
35 protected $bFallback = false;
37 protected $aCountryCodes = false;
39 protected $bBoundedSearch = false;
40 protected $aViewBox = false;
41 protected $aRoutePoints = false;
42 protected $aRouteWidth = false;
44 protected $iMaxRank = 20;
45 protected $iMinAddressRank = 0;
46 protected $iMaxAddressRank = 30;
47 protected $aAddressRankList = array();
48 protected $exactMatchCache = array();
50 protected $sAllowedTypesSQLList = false;
52 protected $sQuery = false;
53 protected $aStructuredQuery = false;
55 protected $oNormalizer = null;
58 public function __construct(&$oDB)
61 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
64 private function normTerm($sTerm)
66 if ($this->oNormalizer === null) {
70 return $this->oNormalizer->transliterate($sTerm);
73 public function setReverseInPlan($bReverse)
75 $this->bReverseInPlan = $bReverse;
78 public function setLanguagePreference($aLangPref)
80 $this->aLangPrefOrder = $aLangPref;
83 public function getMoreUrlParams()
85 if ($this->aStructuredQuery) {
86 $aParams = $this->aStructuredQuery;
88 $aParams = array('q' => $this->sQuery);
91 if ($this->aExcludePlaceIDs) {
92 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
95 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
96 if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
97 if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
99 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
100 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
101 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
102 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
103 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
105 if ($this->fPolygonSimplificationThreshold > 0.0) {
106 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
109 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
110 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
112 if ($this->aCountryCodes) {
113 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
116 if ($this->aViewBox) {
117 $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
118 .','.$this->aViewBox[2].','.$this->aViewBox[1];
124 public function setIncludePolygonAsPoints($b = true)
126 $this->bIncludePolygonAsPoints = $b;
129 public function setIncludePolygonAsText($b = true)
131 $this->bIncludePolygonAsText = $b;
134 public function setIncludePolygonAsGeoJSON($b = true)
136 $this->bIncludePolygonAsGeoJSON = $b;
139 public function setIncludePolygonAsKML($b = true)
141 $this->bIncludePolygonAsKML = $b;
144 public function setIncludePolygonAsSVG($b = true)
146 $this->bIncludePolygonAsSVG = $b;
149 public function setPolygonSimplificationThreshold($f)
151 $this->fPolygonSimplificationThreshold = $f;
154 public function setLimit($iLimit = 10)
156 if ($iLimit > 50) $iLimit = 50;
157 if ($iLimit < 1) $iLimit = 1;
159 $this->iFinalLimit = $iLimit;
160 $this->iLimit = $iLimit + min($iLimit, 10);
163 public function setFeatureType($sFeatureType)
165 switch ($sFeatureType) {
167 $this->setRankRange(4, 4);
170 $this->setRankRange(8, 8);
173 $this->setRankRange(14, 16);
176 $this->setRankRange(8, 20);
181 public function setRankRange($iMin, $iMax)
183 $this->iMinAddressRank = $iMin;
184 $this->iMaxAddressRank = $iMax;
187 public function setViewbox($aViewbox)
189 $this->aViewBox = array_map('floatval', $aViewbox);
191 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
192 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
193 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
194 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
196 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
197 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
199 userError("Bad parameter 'viewbox'. Not a box.");
203 public function setQuery($sQueryString)
205 $this->sQuery = $sQueryString;
206 $this->aStructuredQuery = false;
209 public function getQueryString()
211 return $this->sQuery;
215 public function loadParamArray($oParams)
217 $this->bIncludeAddressDetails
218 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
219 $this->bIncludeExtraTags
220 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
221 $this->bIncludeNameDetails
222 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
224 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
225 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
227 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
228 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
230 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
232 // List of excluded Place IDs - used for more acurate pageing
233 $sExcluded = $oParams->getStringList('exclude_place_ids');
235 foreach ($sExcluded 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 $sFeatureType = $oParams->getString('featureType');
247 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
248 if ($sFeatureType) $this->setFeatureType($sFeatureType);
251 $sCountries = $oParams->getStringList('countrycodes');
253 foreach ($sCountries as $sCountryCode) {
254 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
255 $aCountries[] = strtolower($sCountryCode);
258 if (isset($aCountries))
259 $this->aCountryCodes = $aCountries;
262 $aViewbox = $oParams->getStringList('viewboxlbrt');
264 if (count($aViewbox) != 4) {
265 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
267 $this->setViewbox($aViewbox);
269 $aViewbox = $oParams->getStringList('viewbox');
271 if (count($aViewbox) != 4) {
272 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
274 $this->setViewBox($aViewbox);
276 $aRoute = $oParams->getStringList('route');
277 $fRouteWidth = $oParams->getFloat('routewidth');
278 if ($aRoute && $fRouteWidth) {
279 $this->aRoutePoints = $aRoute;
280 $this->aRouteWidth = $fRouteWidth;
286 public function setQueryFromParams($oParams)
289 $sQuery = $oParams->getString('q');
291 $this->setStructuredQuery(
292 $oParams->getString('amenity'),
293 $oParams->getString('street'),
294 $oParams->getString('city'),
295 $oParams->getString('county'),
296 $oParams->getString('state'),
297 $oParams->getString('country'),
298 $oParams->getString('postalcode')
300 $this->setReverseInPlan(false);
302 $this->setQuery($sQuery);
306 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
308 $sValue = trim($sValue);
309 if (!$sValue) return false;
310 $this->aStructuredQuery[$sKey] = $sValue;
311 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
312 $this->iMinAddressRank = $iNewMinAddressRank;
313 $this->iMaxAddressRank = $iNewMaxAddressRank;
315 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
319 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
321 $this->sQuery = false;
324 $this->iMinAddressRank = 0;
325 $this->iMaxAddressRank = 30;
326 $this->aAddressRankList = array();
328 $this->aStructuredQuery = array();
329 $this->sAllowedTypesSQLList = false;
331 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
332 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
333 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
334 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
335 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
336 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
337 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
339 if (sizeof($this->aStructuredQuery) > 0) {
340 $this->sQuery = join(', ', $this->aStructuredQuery);
341 if ($this->iMaxAddressRank < 30) {
342 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
347 public function fallbackStructuredQuery()
349 if (!$this->aStructuredQuery) return false;
351 $aParams = $this->aStructuredQuery;
353 if (sizeof($aParams) == 1) return false;
355 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
357 foreach ($aOrderToFallback as $sType) {
358 if (isset($aParams[$sType])) {
359 unset($aParams[$sType]);
360 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
368 public function getDetails($aPlaceIDs, $oCtx)
370 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
371 if (sizeof($aPlaceIDs) == 0) return array();
373 $sLanguagePrefArraySQL = getArraySQL(
374 array_map("getDBQuoted", $this->aLangPrefOrder)
377 // Get the details for display (is this a redundant extra step?)
378 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
380 $sImportanceSQL = $oCtx->viewboxImportanceSQL('ST_Collect(centroid)');
381 $sImportanceSQLGeom = $oCtx->viewboxImportanceSQL('geometry');
384 $sSQL .= " osm_type,";
388 $sSQL .= " admin_level,";
389 $sSQL .= " rank_search,";
390 $sSQL .= " rank_address,";
391 $sSQL .= " min(place_id) AS place_id, ";
392 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
393 $sSQL .= " country_code, ";
394 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
395 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
396 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
397 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
398 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
399 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
400 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
401 $sSQL .= " COALESCE(importance,0.75-(rank_search::float/40)) $sImportanceSQL AS importance, ";
402 if ($oCtx->hasNearPoint()) {
403 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
406 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
408 $sSQL .= " place_addressline s, ";
409 $sSQL .= " placex p";
410 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
411 $sSQL .= " AND p.place_id = s.address_place_id ";
412 $sSQL .= " AND s.isaddress ";
413 $sSQL .= " AND p.importance is not null ";
414 $sSQL .= " ) AS addressimportance, ";
416 $sSQL .= " (extratags->'place') AS extra_place ";
417 $sSQL .= " FROM placex";
418 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
420 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
421 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
422 $sSQL .= " OR (extratags->'place') = 'city'";
424 if ($this->aAddressRankList) {
425 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
428 if ($this->sAllowedTypesSQLList) {
429 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
431 $sSQL .= " AND linked_place_id is null ";
432 $sSQL .= " GROUP BY ";
433 $sSQL .= " osm_type, ";
434 $sSQL .= " osm_id, ";
437 $sSQL .= " admin_level, ";
438 $sSQL .= " rank_search, ";
439 $sSQL .= " rank_address, ";
440 $sSQL .= " country_code, ";
441 $sSQL .= " importance, ";
442 if (!$this->bDeDupe) $sSQL .= "place_id,";
443 $sSQL .= " langaddress, ";
444 $sSQL .= " placename, ";
446 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
447 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
448 $sSQL .= " extratags->'place' ";
453 $sSQL .= " 'P' as osm_type,";
454 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
455 $sSQL .= " 'place' as class, 'postcode' as type,";
456 $sSQL .= " null as admin_level, rank_search, rank_address,";
457 $sSQL .= " place_id, parent_place_id, country_code,";
458 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
459 $sSQL .= " postcode as placename,";
460 $sSQL .= " postcode as ref,";
461 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
462 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
463 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
464 $sSQL .= " (0.75-(rank_search::float/40)) $sImportanceSQLGeom AS importance, ";
465 if ($oCtx->hasNearPoint()) {
466 $sSQL .= $oCtx->distanceSQL('geometry')." AS addressimportance,";
469 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
471 $sSQL .= " place_addressline s, ";
472 $sSQL .= " placex p";
473 $sSQL .= " WHERE s.place_id = lp.parent_place_id";
474 $sSQL .= " AND p.place_id = s.address_place_id ";
475 $sSQL .= " AND s.isaddress";
476 $sSQL .= " AND p.importance is not null";
477 $sSQL .= " ) AS addressimportance, ";
479 $sSQL .= " null AS extra_place ";
480 $sSQL .= "FROM location_postcode lp";
481 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
483 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
484 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
485 // with start- and endnumber, the common osm housenumbers are usually saved as points
488 $length = count($aPlaceIDs);
489 foreach ($aPlaceIDs as $placeID => $housenumber) {
491 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
492 if ($i<$length) $sHousenumbers .= ", ";
495 if (CONST_Use_US_Tiger_Data) {
496 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
499 $sSQL .= " 'T' AS osm_type, ";
500 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
501 $sSQL .= " 'place' AS class, ";
502 $sSQL .= " 'house' AS type, ";
503 $sSQL .= " null AS admin_level, ";
504 $sSQL .= " 30 AS rank_search, ";
505 $sSQL .= " 30 AS rank_address, ";
506 $sSQL .= " min(place_id) AS place_id, ";
507 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
508 $sSQL .= " 'us' AS country_code, ";
509 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
510 $sSQL .= " null AS placename, ";
511 $sSQL .= " null AS ref, ";
512 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
513 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
514 $sSQL .= " avg(st_x(centroid)) AS lon, ";
515 $sSQL .= " avg(st_y(centroid)) AS lat,";
516 $sSQL .= " -1.15".$sImportanceSQL." AS importance, ";
517 if ($oCtx->hasNearPoint()) {
518 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
521 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
523 $sSQL .= " place_addressline s, ";
524 $sSQL .= " placex p";
525 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
526 $sSQL .= " AND p.place_id = s.address_place_id ";
527 $sSQL .= " AND s.isaddress";
528 $sSQL .= " AND p.importance is not null";
529 $sSQL .= " ) AS addressimportance, ";
531 $sSQL .= " null AS extra_place ";
533 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
534 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
535 $sSQL .= " parent_place_id, ";
536 $sSQL .= " housenumber_for_place";
538 $sSQL .= " location_property_tiger ";
539 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
541 $sSQL .= " housenumber_for_place>=0";
542 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
543 $sSQL .= " ) AS blub"; //postgres wants an alias here
544 $sSQL .= " GROUP BY";
545 $sSQL .= " place_id, ";
546 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
547 if (!$this->bDeDupe) $sSQL .= ", place_id ";
550 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
553 $sSQL .= " 'W' AS osm_type, ";
554 $sSQL .= " osm_id, ";
555 $sSQL .= " 'place' AS class, ";
556 $sSQL .= " 'house' AS type, ";
557 $sSQL .= " null AS admin_level, ";
558 $sSQL .= " 30 AS rank_search, ";
559 $sSQL .= " 30 AS rank_address, ";
560 $sSQL .= " min(place_id) as place_id, ";
561 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
562 $sSQL .= " country_code, ";
563 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
564 $sSQL .= " null AS placename, ";
565 $sSQL .= " null AS ref, ";
566 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
567 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
568 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
569 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
570 $sSQL .= " -0.1".$sImportanceSQL." AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
571 if ($oCtx->hasNearPoint()) {
572 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
576 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
578 $sSQL .= " place_addressline s, ";
579 $sSQL .= " placex p";
580 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
581 $sSQL .= " AND p.place_id = s.address_place_id ";
582 $sSQL .= " AND s.isaddress ";
583 $sSQL .= " AND p.importance is not null";
584 $sSQL .= " ) AS addressimportance,";
586 $sSQL .= " null AS extra_place ";
589 $sSQL .= " osm_id, ";
590 $sSQL .= " place_id, ";
591 $sSQL .= " country_code, ";
592 $sSQL .= " CASE "; // interpolate the housenumbers here
593 $sSQL .= " WHEN startnumber != endnumber ";
594 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
595 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
596 $sSQL .= " END as centroid, ";
597 $sSQL .= " parent_place_id, ";
598 $sSQL .= " housenumber_for_place ";
600 $sSQL .= " location_property_osmline ";
601 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
603 $sSQL .= " WHERE housenumber_for_place>=0 ";
604 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
605 $sSQL .= " ) as blub"; //postgres wants an alias here
606 $sSQL .= " GROUP BY ";
607 $sSQL .= " osm_id, ";
608 $sSQL .= " place_id, ";
609 $sSQL .= " housenumber_for_place, ";
610 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
611 if (!$this->bDeDupe) $sSQL .= ", place_id ";
613 if (CONST_Use_Aux_Location_data) {
616 $sSQL .= " 'L' AS osm_type, ";
617 $sSQL .= " place_id AS osm_id, ";
618 $sSQL .= " 'place' AS class,";
619 $sSQL .= " 'house' AS type, ";
620 $sSQL .= " null AS admin_level, ";
621 $sSQL .= " 0 AS rank_search,";
622 $sSQL .= " 0 AS rank_address, ";
623 $sSQL .= " min(place_id) AS place_id,";
624 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
625 $sSQL .= " 'us' AS country_code, ";
626 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
627 $sSQL .= " null AS placename, ";
628 $sSQL .= " null AS ref, ";
629 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
630 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
631 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
632 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
633 $sSQL .= " -1.10".$sImportanceSQL." AS importance, ";
634 if ($oCtx->hasNearPoint()) {
635 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
638 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
640 $sSQL .= " place_addressline s, ";
641 $sSQL .= " placex p";
642 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
643 $sSQL .= " AND p.place_id = s.address_place_id ";
644 $sSQL .= " AND s.isaddress";
645 $sSQL .= " AND p.importance is not null";
646 $sSQL .= " ) AS addressimportance, ";
648 $sSQL .= " null AS extra_place ";
649 $sSQL .= " FROM location_property_aux ";
650 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
651 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
652 $sSQL .= " GROUP BY ";
653 $sSQL .= " place_id, ";
654 if (!$this->bDeDupe) $sSQL .= "place_id, ";
655 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
659 $sSQL .= " order by importance desc";
664 $aSearchResults = chksql(
665 $this->oDB->getAll($sSQL),
666 "Could not get details for place."
669 return $aSearchResults;
672 public function getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bIsStructured, $sNormQuery)
675 Calculate all searches using aValidTokens i.e.
676 'Wodsworth Road, Sheffield' =>
680 0 1 (wodsworth)(road)
683 Score how good the search is so they can be ordered
687 foreach ($aPhrases as $iPhrase => $oPhrase) {
688 $aNewPhraseSearches = array();
689 $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
691 foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
692 // Too many permutations - too expensive
693 if ($iWordSet > 120) break;
695 $aWordsetSearches = $aSearches;
697 // Add all words from this wordset
698 foreach ($aWordset as $iToken => $sToken) {
699 //echo "<br><b>$sToken</b>";
700 $aNewWordsetSearches = array();
702 foreach ($aWordsetSearches as $oCurrentSearch) {
704 //var_dump($oCurrentSearch);
707 // If the token is valid
708 if (isset($aValidTokens[' '.$sToken])) {
709 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
710 // Recheck if the original word shows up in the query.
711 $bWordInQuery = false;
712 if (isset($aSearchTerm['word']) && $aSearchTerm['word']) {
713 $bWordInQuery = strpos(
715 $this->normTerm($aSearchTerm['word'])
718 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
721 isset($aValidTokens[$sToken])
722 && strpos($sToken, ' ') === false,
724 $iToken == 0 && $iPhrase == 0,
726 $iToken + 1 == sizeof($aWordset)
727 && $iPhrase + 1 == sizeof($aPhrases),
731 foreach ($aNewSearches as $oSearch) {
732 if ($oSearch->getRank() < $this->iMaxRank) {
733 $aNewWordsetSearches[] = $oSearch;
738 // Look for partial matches.
739 // Note that there is no point in adding country terms here
740 // because country is omitted in the address.
741 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
742 // Allow searching for a word - but at extra cost
743 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
744 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
748 $aWordFrequencyScores,
749 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
752 foreach ($aNewSearches as $oSearch) {
753 if ($oSearch->getRank() < $this->iMaxRank) {
754 $aNewWordsetSearches[] = $oSearch;
761 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
762 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
764 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
766 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
767 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
769 $aSearchHash = array();
770 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
771 $sHash = serialize($aSearch);
772 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
773 else $aSearchHash[$sHash] = 1;
776 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
779 // Re-group the searches by their score, junk anything over 20 as just not worth trying
780 $aGroupedSearches = array();
781 foreach ($aNewPhraseSearches as $aSearch) {
782 $iRank = $aSearch->getRank();
783 if ($iRank < $this->iMaxRank) {
784 if (!isset($aGroupedSearches[$iRank])) {
785 $aGroupedSearches[$iRank] = array();
787 $aGroupedSearches[$iRank][] = $aSearch;
790 ksort($aGroupedSearches);
793 $aSearches = array();
794 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
795 $iSearchCount += sizeof($aNewSearches);
796 $aSearches = array_merge($aSearches, $aNewSearches);
797 if ($iSearchCount > 50) break;
800 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
803 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
804 $aGroupedSearches = array();
805 foreach ($aSearches as $oSearch) {
806 if (!$oSearch->isValidSearch($this->aCountryCodes)) {
810 $iRank = $oSearch->addToRank($iGlobalRank);
811 if (!isset($aGroupedSearches[$iRank])) {
812 $aGroupedSearches[$iRank] = array();
814 $aGroupedSearches[$iRank][] = $oSearch;
816 ksort($aGroupedSearches);
818 return $aGroupedSearches;
821 /* Perform the actual query lookup.
823 Returns an ordered list of results, each with the following fields:
824 osm_type: type of corresponding OSM object
828 P - postcode (internally computed)
829 osm_id: id of corresponding OSM object
830 class: general object class (corresponds to tag key of primary OSM tag)
831 type: subclass of object (corresponds to tag value of primary OSM tag)
832 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
833 rank_search: rank in search hierarchy
834 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
835 rank_address: rank in address hierarchy (determines orer in address)
836 place_id: internal key (may differ between different instances)
837 country_code: ISO country code
838 langaddress: localized full address
839 placename: localized name of object
840 ref: content of ref tag (if available)
843 importance: importance of place based on Wikipedia link count
844 addressimportance: cumulated importance of address elements
845 extra_place: type of place (for admin boundaries, if there is a place tag)
846 aBoundingBox: bounding Box
847 label: short description of the object class/type (English only)
848 name: full name (currently the same as langaddress)
849 foundorder: secondary ordering for places with same importance
853 public function lookup()
855 if (!$this->sQuery && !$this->aStructuredQuery) return array();
857 $oCtx = new SearchContext();
859 if ($this->aRoutePoints) {
860 $oCtx->setViewboxFromRoute(
864 $this->bBoundedSearch
866 } elseif ($this->aViewBox) {
867 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
869 if ($this->aExcludePlaceIDs) {
870 $oCtx->setExcludeList($this->aExcludePlaceIDs);
872 if ($this->aCountryCodes) {
873 $oCtx->setCountryList($this->aCountryCodes);
876 $sNormQuery = $this->normTerm($this->sQuery);
877 $sLanguagePrefArraySQL = getArraySQL(
878 array_map("getDBQuoted", $this->aLangPrefOrder)
881 $sQuery = $this->sQuery;
882 if (!preg_match('//u', $sQuery)) {
883 userError("Query string is not UTF-8 encoded.");
886 // Conflicts between US state abreviations and various words for 'the' in different languages
887 if (isset($this->aLangPrefOrder['name:en'])) {
888 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
889 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
890 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
893 // Do we have anything that looks like a lat/lon pair?
894 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
896 $aSearchResults = array();
897 if ($sQuery || $this->aStructuredQuery) {
898 // Start with a single blank search
899 $aSearches = array(new SearchDescription($oCtx));
902 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
908 '/\\[([\\w ]*)\\]/u',
913 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
914 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
915 if (!$sSpecialTerm) {
916 $sSpecialTerm = $aSpecialTerm[1];
920 if (!$sSpecialTerm && $this->aStructuredQuery
921 && isset($this->aStructuredQuery['amenity'])) {
922 $sSpecialTerm = $this->aStructuredQuery['amenity'];
923 unset($this->aStructuredQuery['amenity']);
926 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
927 $sSpecialTerm = pg_escape_string($sSpecialTerm);
929 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
930 "Cannot decode query. Wrong encoding?"
932 $sSQL = 'SELECT class, type FROM word ';
933 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
934 $sSQL .= ' AND class is not null AND class not in (\'place\')';
935 if (CONST_Debug) var_Dump($sSQL);
936 $aSearchWords = chksql($this->oDB->getAll($sSQL));
937 $aNewSearches = array();
938 foreach ($aSearches as $oSearch) {
939 foreach ($aSearchWords as $aSearchTerm) {
940 $oNewSearch = clone $oSearch;
941 $oNewSearch->setPoiSearch(
943 $aSearchTerm['class'],
946 $aNewSearches[] = $oNewSearch;
949 $aSearches = $aNewSearches;
952 // Split query into phrases
953 // Commas are used to reduce the search space by indicating where phrases split
954 if ($this->aStructuredQuery) {
955 $aInPhrases = $this->aStructuredQuery;
956 $bStructuredPhrases = true;
958 $aInPhrases = explode(',', $sQuery);
959 $bStructuredPhrases = false;
962 // Convert each phrase to standard form
963 // Create a list of standard words
964 // Get all 'sets' of words
965 // Generate a complete list of all
968 foreach ($aInPhrases as $iPhrase => $sPhrase) {
970 $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
971 "Cannot normalize query string (is it a UTF-8 string?)"
973 if (trim($sPhrase)) {
974 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
975 $oPhrase->addTokens($aTokens);
976 $aPhrases[] = $oPhrase;
980 if (sizeof($aTokens)) {
981 // Check which tokens we have, get the ID numbers
982 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
983 $sSQL .= ' FROM word ';
984 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
986 if (CONST_Debug) var_Dump($sSQL);
988 $aValidTokens = array();
989 $aDatabaseWords = chksql(
990 $this->oDB->getAll($sSQL),
991 "Could not get word tokens."
993 $aPossibleMainWordIDs = array();
994 $aWordFrequencyScores = array();
995 foreach ($aDatabaseWords as $aToken) {
996 // Very special case - require 2 letter country param to match the country code found
997 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
998 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1003 if (isset($aValidTokens[$aToken['word_token']])) {
1004 $aValidTokens[$aToken['word_token']][] = $aToken;
1006 $aValidTokens[$aToken['word_token']] = array($aToken);
1008 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1009 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1011 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1013 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1014 foreach ($aTokens as $sToken) {
1015 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1016 if (isset($aValidTokens[$aData[1]])) {
1017 foreach ($aValidTokens[$aData[1]] as $aToken) {
1018 if (!$aToken['class']) {
1019 if (isset($aValidTokens[$sToken])) {
1020 $aValidTokens[$sToken][] = $aToken;
1022 $aValidTokens[$sToken] = array($aToken);
1030 foreach ($aTokens as $sToken) {
1031 // Unknown single word token with a number - assume it is a house number
1032 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1033 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1037 // Any words that have failed completely?
1038 // TODO: suggestions
1040 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1042 if ($this->bReverseInPlan) {
1043 // Reverse phrase array and also reverse the order of the wordsets in
1044 // the first and final phrase. Don't bother about phrases in the middle
1045 // because order in the address doesn't matter.
1046 $aPhrases = array_reverse($aPhrases);
1047 $aPhrases[0]->invertWordSets();
1048 if (sizeof($aPhrases) > 1) {
1049 $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
1051 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1053 foreach ($aGroupedSearches as $aSearches) {
1054 foreach ($aSearches as $aSearch) {
1055 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1056 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1058 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1062 $aGroupedSearches = $aReverseGroupedSearches;
1063 ksort($aGroupedSearches);
1066 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1067 $aGroupedSearches = array();
1068 foreach ($aSearches as $aSearch) {
1069 if ($aSearch->getRank() < $this->iMaxRank) {
1070 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1071 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1074 ksort($aGroupedSearches);
1077 // Filter out duplicate searches
1078 $aSearchHash = array();
1079 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1080 foreach ($aSearches as $iSearch => $aSearch) {
1081 $sHash = serialize($aSearch);
1082 if (isset($aSearchHash[$sHash])) {
1083 unset($aGroupedSearches[$iGroup][$iSearch]);
1084 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1086 $aSearchHash[$sHash] = 1;
1091 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1093 // Start the search process
1094 // array with: placeid => -1 | tiger-housenumber
1095 $aResultPlaceIDs = array();
1098 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1100 foreach ($aSearches as $oSearch) {
1104 echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1105 _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1108 $aRes = $oSearch->query(
1110 $aWordFrequencyScores,
1111 $this->exactMatchCache,
1112 $this->iMinAddressRank,
1113 $this->iMaxAddressRank,
1117 foreach ($aRes['IDs'] as $iPlaceID) {
1118 // array for placeID => -1 | Tiger housenumber
1119 $aResultPlaceIDs[$iPlaceID] = $aRes['houseNumber'];
1121 if ($iQueryLoop > 20) break;
1124 if (sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1125 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1126 // reduces the number of place ids, like a filter
1127 // rank_address is 30 for interpolated housenumbers
1128 $sWherePlaceId = 'WHERE place_id in (';
1129 $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1131 $sSQL = "SELECT place_id ";
1132 $sSQL .= "FROM placex ".$sWherePlaceId;
1134 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1135 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1136 $sSQL .= " OR (extratags->'place') = 'city'";
1138 if ($this->aAddressRankList) {
1139 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1141 $sSQL .= " ) UNION ";
1142 $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1143 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1144 if ($this->aAddressRankList) {
1145 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1148 if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1150 $sSQL .= " SELECT place_id ";
1151 $sSQL .= " FROM location_property_tiger ".$sWherePlaceId;
1153 if ($this->iMaxAddressRank == 30) {
1155 $sSQL .= " SELECT place_id ";
1156 $sSQL .= " FROM location_property_osmline ".$sWherePlaceId;
1158 if (CONST_Debug) var_dump($sSQL);
1159 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1161 foreach ($aFilteredPlaceIDs as $placeID) {
1162 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1164 $aResultPlaceIDs = $tempIDs;
1167 if (sizeof($aResultPlaceIDs)) break;
1168 if ($iGroupLoop > 4) break;
1169 if ($iQueryLoop > 30) break;
1172 // Did we find anything?
1173 if (sizeof($aResultPlaceIDs)) {
1174 $aSearchResults = $this->getDetails($aResultPlaceIDs, $oCtx);
1177 // Just interpret as a reverse geocode
1178 $oReverse = new ReverseGeocode($this->oDB);
1179 $oReverse->setZoom(18);
1181 $aLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
1183 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1185 if ($aLookup['place_id']) {
1186 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1), $oCtx);
1187 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1189 $aSearchResults = array();
1194 if (!sizeof($aSearchResults)) {
1195 if ($this->bFallback) {
1196 if ($this->fallbackStructuredQuery()) {
1197 return $this->lookup();
1204 $aClassType = getClassTypesWithImportance();
1205 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1206 foreach ($aRecheckWords as $i => $sWord) {
1207 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1211 echo '<i>Recheck words:<\i>';
1212 var_dump($aRecheckWords);
1215 $oPlaceLookup = new PlaceLookup($this->oDB);
1216 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1217 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1218 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1219 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1220 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1221 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1223 foreach ($aSearchResults as $iResNum => $aResult) {
1225 $fDiameter = getResultDiameter($aResult);
1227 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1228 if ($aOutlineResult) {
1229 $aResult = array_merge($aResult, $aOutlineResult);
1232 if ($aResult['extra_place'] == 'city') {
1233 $aResult['class'] = 'place';
1234 $aResult['type'] = 'city';
1235 $aResult['rank_search'] = 16;
1238 // Is there an icon set for this type of result?
1239 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1240 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1242 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1245 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1246 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1248 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1249 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1250 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1252 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1254 // if tag '&addressdetails=1' is set in query
1255 if ($this->bIncludeAddressDetails) {
1256 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1257 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1258 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1259 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1263 if ($this->bIncludeExtraTags) {
1264 if ($aResult['extra']) {
1265 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1267 $aResult['sExtraTags'] = (object) array();
1271 if ($this->bIncludeNameDetails) {
1272 if ($aResult['names']) {
1273 $aResult['sNameDetails'] = json_decode($aResult['names']);
1275 $aResult['sNameDetails'] = (object) array();
1279 $aResult['name'] = $aResult['langaddress'];
1281 if ($oCtx->hasNearPoint())
1283 $aResult['importance'] = 0.001;
1284 $aResult['foundorder'] = $aResult['addressimportance'];
1286 // Adjust importance for the number of exact string matches in the result
1287 $aResult['importance'] = max(0.001, $aResult['importance']);
1289 $sAddress = $aResult['langaddress'];
1290 foreach ($aRecheckWords as $i => $sWord) {
1291 if (stripos($sAddress, $sWord)!==false) {
1293 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1297 $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
1299 // secondary ordering (for results with same importance (the smaller the better):
1300 // - approximate importance of address parts
1301 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1302 // - number of exact matches from the query
1303 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1304 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1305 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1306 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1308 // - importance of the class/type
1309 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1310 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1312 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1314 $aResult['foundorder'] += 0.01;
1317 if (CONST_Debug) var_dump($aResult);
1318 $aSearchResults[$iResNum] = $aResult;
1320 uasort($aSearchResults, 'byImportance');
1322 $aOSMIDDone = array();
1323 $aClassTypeNameDone = array();
1324 $aToFilter = $aSearchResults;
1325 $aSearchResults = array();
1328 foreach ($aToFilter as $iResNum => $aResult) {
1329 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1331 $fLat = $aResult['lat'];
1332 $fLon = $aResult['lon'];
1333 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1336 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1337 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1339 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1340 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1341 $aSearchResults[] = $aResult;
1344 // Absolute limit on number of results
1345 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1348 return $aSearchResults;