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();
49 protected $sAllowedTypesSQLList = false;
51 protected $sQuery = false;
52 protected $aStructuredQuery = false;
54 protected $oNormalizer = null;
57 public function __construct(&$oDB)
60 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
63 private function normTerm($sTerm)
65 if ($this->oNormalizer === null) {
69 return $this->oNormalizer->transliterate($sTerm);
72 public function setReverseInPlan($bReverse)
74 $this->bReverseInPlan = $bReverse;
77 public function setLanguagePreference($aLangPref)
79 $this->aLangPrefOrder = $aLangPref;
82 public function getMoreUrlParams()
84 if ($this->aStructuredQuery) {
85 $aParams = $this->aStructuredQuery;
87 $aParams = array('q' => $this->sQuery);
90 if ($this->aExcludePlaceIDs) {
91 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
94 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
95 if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
96 if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
98 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
99 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
100 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
101 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
102 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
104 if ($this->fPolygonSimplificationThreshold > 0.0) {
105 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
108 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
109 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
111 if ($this->aCountryCodes) {
112 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
115 if ($this->aViewBox) {
116 $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
117 .','.$this->aViewBox[2].','.$this->aViewBox[1];
123 public function setIncludePolygonAsPoints($b = true)
125 $this->bIncludePolygonAsPoints = $b;
128 public function setIncludePolygonAsText($b = true)
130 $this->bIncludePolygonAsText = $b;
133 public function setIncludePolygonAsGeoJSON($b = true)
135 $this->bIncludePolygonAsGeoJSON = $b;
138 public function setIncludePolygonAsKML($b = true)
140 $this->bIncludePolygonAsKML = $b;
143 public function setIncludePolygonAsSVG($b = true)
145 $this->bIncludePolygonAsSVG = $b;
148 public function setPolygonSimplificationThreshold($f)
150 $this->fPolygonSimplificationThreshold = $f;
153 public function setLimit($iLimit = 10)
155 if ($iLimit > 50) $iLimit = 50;
156 if ($iLimit < 1) $iLimit = 1;
158 $this->iFinalLimit = $iLimit;
159 $this->iLimit = $iLimit + min($iLimit, 10);
162 public function setFeatureType($sFeatureType)
164 switch ($sFeatureType) {
166 $this->setRankRange(4, 4);
169 $this->setRankRange(8, 8);
172 $this->setRankRange(14, 16);
175 $this->setRankRange(8, 20);
180 public function setRankRange($iMin, $iMax)
182 $this->iMinAddressRank = $iMin;
183 $this->iMaxAddressRank = $iMax;
186 public function setViewbox($aViewbox)
188 $this->aViewBox = array_map('floatval', $aViewbox);
190 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
191 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
192 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
193 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
195 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
196 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
198 userError("Bad parameter 'viewbox'. Not a box.");
202 public function setQuery($sQueryString)
204 $this->sQuery = $sQueryString;
205 $this->aStructuredQuery = false;
208 public function getQueryString()
210 return $this->sQuery;
214 public function loadParamArray($oParams)
216 $this->bIncludeAddressDetails
217 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
218 $this->bIncludeExtraTags
219 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
220 $this->bIncludeNameDetails
221 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
223 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
224 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
226 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
227 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
229 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
231 // List of excluded Place IDs - used for more acurate pageing
232 $sExcluded = $oParams->getStringList('exclude_place_ids');
234 foreach ($sExcluded as $iExcludedPlaceID) {
235 $iExcludedPlaceID = (int)$iExcludedPlaceID;
236 if ($iExcludedPlaceID)
237 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
240 if (isset($aExcludePlaceIDs))
241 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
244 // Only certain ranks of feature
245 $sFeatureType = $oParams->getString('featureType');
246 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
247 if ($sFeatureType) $this->setFeatureType($sFeatureType);
250 $sCountries = $oParams->getStringList('countrycodes');
252 foreach ($sCountries as $sCountryCode) {
253 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
254 $aCountries[] = strtolower($sCountryCode);
257 if (isset($aCountries))
258 $this->aCountryCodes = $aCountries;
261 $aViewbox = $oParams->getStringList('viewboxlbrt');
263 if (count($aViewbox) != 4) {
264 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
266 $this->setViewbox($aViewbox);
268 $aViewbox = $oParams->getStringList('viewbox');
270 if (count($aViewbox) != 4) {
271 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
273 $this->setViewBox($aViewbox);
275 $aRoute = $oParams->getStringList('route');
276 $fRouteWidth = $oParams->getFloat('routewidth');
277 if ($aRoute && $fRouteWidth) {
278 $this->aRoutePoints = $aRoute;
279 $this->aRouteWidth = $fRouteWidth;
285 public function setQueryFromParams($oParams)
288 $sQuery = $oParams->getString('q');
290 $this->setStructuredQuery(
291 $oParams->getString('amenity'),
292 $oParams->getString('street'),
293 $oParams->getString('city'),
294 $oParams->getString('county'),
295 $oParams->getString('state'),
296 $oParams->getString('country'),
297 $oParams->getString('postalcode')
299 $this->setReverseInPlan(false);
301 $this->setQuery($sQuery);
305 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
307 $sValue = trim($sValue);
308 if (!$sValue) return false;
309 $this->aStructuredQuery[$sKey] = $sValue;
310 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
311 $this->iMinAddressRank = $iNewMinAddressRank;
312 $this->iMaxAddressRank = $iNewMaxAddressRank;
314 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
318 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
320 $this->sQuery = false;
323 $this->iMinAddressRank = 0;
324 $this->iMaxAddressRank = 30;
325 $this->aAddressRankList = array();
327 $this->aStructuredQuery = array();
328 $this->sAllowedTypesSQLList = false;
330 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
331 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
332 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
333 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
334 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
335 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
336 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
338 if (sizeof($this->aStructuredQuery) > 0) {
339 $this->sQuery = join(', ', $this->aStructuredQuery);
340 if ($this->iMaxAddressRank < 30) {
341 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
346 public function fallbackStructuredQuery()
348 if (!$this->aStructuredQuery) return false;
350 $aParams = $this->aStructuredQuery;
352 if (sizeof($aParams) == 1) return false;
354 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
356 foreach ($aOrderToFallback as $sType) {
357 if (isset($aParams[$sType])) {
358 unset($aParams[$sType]);
359 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
367 public function getDetails($aResults, $oCtx)
369 // Get the details for display (is this a redundant extra step?)
370 //$aResults is an array of Result objects
371 if (sizeof($aResults) == 0) return array();
373 $sLanguagePrefArraySQL = getArraySQL(
374 array_map("getDBQuoted", $this->aLangPrefOrder)
377 $sImportanceSQL = $oCtx->viewboxImportanceSQL('ST_Collect(centroid)');
378 $sImportanceSQLGeom = $oCtx->viewboxImportanceSQL('geometry');
380 $aSubSelects = array();
382 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
385 $sSQL .= " osm_type,";
389 $sSQL .= " admin_level,";
390 $sSQL .= " rank_search,";
391 $sSQL .= " rank_address,";
392 $sSQL .= " min(place_id) AS place_id, ";
393 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
394 $sSQL .= " country_code, ";
395 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
396 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
397 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
398 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
399 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
400 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
401 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
402 $sSQL .= " COALESCE(importance,0.75-(rank_search::float/40)) $sImportanceSQL AS importance, ";
403 if ($oCtx->hasNearPoint()) {
404 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
407 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
409 $sSQL .= " place_addressline s, ";
410 $sSQL .= " placex p";
411 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
412 $sSQL .= " AND p.place_id = s.address_place_id ";
413 $sSQL .= " AND s.isaddress ";
414 $sSQL .= " AND p.importance is not null ";
415 $sSQL .= " ) AS addressimportance, ";
417 $sSQL .= " (extratags->'place') AS extra_place ";
418 $sSQL .= " FROM placex";
419 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
421 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
422 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
423 $sSQL .= " OR (extratags->'place') = 'city'";
425 if ($this->aAddressRankList) {
426 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
429 if ($this->sAllowedTypesSQLList) {
430 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
432 $sSQL .= " AND linked_place_id is null ";
433 $sSQL .= " GROUP BY ";
434 $sSQL .= " osm_type, ";
435 $sSQL .= " osm_id, ";
438 $sSQL .= " admin_level, ";
439 $sSQL .= " rank_search, ";
440 $sSQL .= " rank_address, ";
441 $sSQL .= " country_code, ";
442 $sSQL .= " importance, ";
443 if (!$this->bDeDupe) $sSQL .= "place_id,";
444 $sSQL .= " langaddress, ";
445 $sSQL .= " placename, ";
447 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
448 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
449 $sSQL .= " extratags->'place' ";
451 $aSubSelects[] = $sSQL;
455 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
458 $sSQL .= " 'P' as osm_type,";
459 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
460 $sSQL .= " 'place' as class, 'postcode' as type,";
461 $sSQL .= " null as admin_level, rank_search, rank_address,";
462 $sSQL .= " place_id, parent_place_id, country_code,";
463 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
464 $sSQL .= " postcode as placename,";
465 $sSQL .= " postcode as ref,";
466 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
467 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
468 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
469 $sSQL .= " (0.75-(rank_search::float/40)) $sImportanceSQLGeom AS importance, ";
470 if ($oCtx->hasNearPoint()) {
471 $sSQL .= $oCtx->distanceSQL('geometry')." AS addressimportance,";
474 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
476 $sSQL .= " place_addressline s, ";
477 $sSQL .= " placex p";
478 $sSQL .= " WHERE s.place_id = lp.parent_place_id";
479 $sSQL .= " AND p.place_id = s.address_place_id ";
480 $sSQL .= " AND s.isaddress";
481 $sSQL .= " AND p.importance is not null";
482 $sSQL .= " ) AS addressimportance, ";
484 $sSQL .= " null AS extra_place ";
485 $sSQL .= "FROM location_postcode lp";
486 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
488 $aSubSelects[] = $sSQL;
491 // All other tables are rank 30 only.
492 if ($this->iMaxAddressRank == 30) {
494 if (CONST_Use_US_Tiger_Data) {
495 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
497 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
498 // Tiger search only if a housenumber was searched and if it was found
499 // (realized through a join)
501 $sSQL .= " 'T' AS osm_type, ";
502 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
503 $sSQL .= " 'place' AS class, ";
504 $sSQL .= " 'house' AS type, ";
505 $sSQL .= " null AS admin_level, ";
506 $sSQL .= " 30 AS rank_search, ";
507 $sSQL .= " 30 AS rank_address, ";
508 $sSQL .= " min(place_id) AS place_id, ";
509 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
510 $sSQL .= " 'us' AS country_code, ";
511 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
512 $sSQL .= " null AS placename, ";
513 $sSQL .= " null AS ref, ";
514 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
515 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
516 $sSQL .= " avg(st_x(centroid)) AS lon, ";
517 $sSQL .= " avg(st_y(centroid)) AS lat,";
518 $sSQL .= " -1.15".$sImportanceSQL." AS importance, ";
519 if ($oCtx->hasNearPoint()) {
520 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
523 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
525 $sSQL .= " place_addressline s, ";
526 $sSQL .= " placex p";
527 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
528 $sSQL .= " AND p.place_id = s.address_place_id ";
529 $sSQL .= " AND s.isaddress";
530 $sSQL .= " AND p.importance is not null";
531 $sSQL .= " ) AS addressimportance, ";
533 $sSQL .= " null AS extra_place ";
535 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
536 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
537 $sSQL .= " parent_place_id, ";
538 $sSQL .= " housenumber_for_place";
540 $sSQL .= " location_property_tiger ";
541 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
543 $sSQL .= " housenumber_for_place >= startnumber";
544 $sSQL .= " AND housenumber_for_place <= endnumber";
545 $sSQL .= " ) AS blub"; //postgres wants an alias here
546 $sSQL .= " GROUP BY";
547 $sSQL .= " place_id, ";
548 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
549 if (!$this->bDeDupe) $sSQL .= ", place_id ";
551 $aSubSelects[] = $sSQL;
555 // osmline - interpolated housenumbers
556 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
558 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
559 // interpolation line search only if a housenumber was searched
560 // (realized through a join)
562 $sSQL .= " 'W' AS osm_type, ";
563 $sSQL .= " osm_id, ";
564 $sSQL .= " 'place' AS class, ";
565 $sSQL .= " 'house' AS type, ";
566 $sSQL .= " null AS admin_level, ";
567 $sSQL .= " 30 AS rank_search, ";
568 $sSQL .= " 30 AS rank_address, ";
569 $sSQL .= " min(place_id) as place_id, ";
570 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
571 $sSQL .= " country_code, ";
572 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
573 $sSQL .= " null AS placename, ";
574 $sSQL .= " null AS ref, ";
575 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
576 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
577 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
578 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
579 $sSQL .= " -0.1".$sImportanceSQL." AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
580 if ($oCtx->hasNearPoint()) {
581 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
585 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
587 $sSQL .= " place_addressline s, ";
588 $sSQL .= " placex p";
589 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
590 $sSQL .= " AND p.place_id = s.address_place_id ";
591 $sSQL .= " AND s.isaddress ";
592 $sSQL .= " AND p.importance is not null";
593 $sSQL .= " ) AS addressimportance,";
595 $sSQL .= " null AS extra_place ";
598 $sSQL .= " osm_id, ";
599 $sSQL .= " place_id, ";
600 $sSQL .= " country_code, ";
601 $sSQL .= " CASE "; // interpolate the housenumbers here
602 $sSQL .= " WHEN startnumber != endnumber ";
603 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
604 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
605 $sSQL .= " END as centroid, ";
606 $sSQL .= " parent_place_id, ";
607 $sSQL .= " housenumber_for_place ";
609 $sSQL .= " location_property_osmline ";
610 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
612 $sSQL .= " WHERE housenumber_for_place>=0 ";
613 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
614 $sSQL .= " ) as blub"; //postgres wants an alias here
615 $sSQL .= " GROUP BY ";
616 $sSQL .= " osm_id, ";
617 $sSQL .= " place_id, ";
618 $sSQL .= " housenumber_for_place, ";
619 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
620 if (!$this->bDeDupe) $sSQL .= ", place_id ";
622 $aSubSelects[] = $sSQL;
625 if (CONST_Use_Aux_Location_data) {
626 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
628 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
630 $sSQL .= " 'L' AS osm_type, ";
631 $sSQL .= " place_id AS osm_id, ";
632 $sSQL .= " 'place' AS class,";
633 $sSQL .= " 'house' AS type, ";
634 $sSQL .= " null AS admin_level, ";
635 $sSQL .= " 0 AS rank_search,";
636 $sSQL .= " 0 AS rank_address, ";
637 $sSQL .= " min(place_id) AS place_id,";
638 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
639 $sSQL .= " 'us' AS country_code, ";
640 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
641 $sSQL .= " null AS placename, ";
642 $sSQL .= " null AS ref, ";
643 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
644 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
645 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
646 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
647 $sSQL .= " -1.10".$sImportanceSQL." AS importance, ";
648 if ($oCtx->hasNearPoint()) {
649 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
652 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
654 $sSQL .= " place_addressline s, ";
655 $sSQL .= " placex p";
656 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
657 $sSQL .= " AND p.place_id = s.address_place_id ";
658 $sSQL .= " AND s.isaddress";
659 $sSQL .= " AND p.importance is not null";
660 $sSQL .= " ) AS addressimportance, ";
662 $sSQL .= " null AS extra_place ";
663 $sSQL .= " FROM location_property_aux ";
664 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
665 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
666 $sSQL .= " GROUP BY ";
667 $sSQL .= " place_id, ";
668 if (!$this->bDeDupe) $sSQL .= "place_id, ";
669 $sSQL .= " langaddress ";
671 $aSubSelects[] = $sSQL;
676 if (!sizeof($aSubSelects)) {
680 $sSQL = join(' UNION ', $aSubSelects)." order by importance desc";
685 $aSearchResults = chksql(
686 $this->oDB->getAll($sSQL),
687 "Could not get details for place."
690 return $aSearchResults;
693 public function getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bIsStructured)
696 Calculate all searches using aValidTokens i.e.
697 'Wodsworth Road, Sheffield' =>
701 0 1 (wodsworth)(road)
704 Score how good the search is so they can be ordered
708 foreach ($aPhrases as $iPhrase => $oPhrase) {
709 $aNewPhraseSearches = array();
710 $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
712 foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
713 // Too many permutations - too expensive
714 if ($iWordSet > 120) break;
716 $aWordsetSearches = $aSearches;
718 // Add all words from this wordset
719 foreach ($aWordset as $iToken => $sToken) {
720 //echo "<br><b>$sToken</b>";
721 $aNewWordsetSearches = array();
723 foreach ($aWordsetSearches as $oCurrentSearch) {
725 //var_dump($oCurrentSearch);
728 // If the token is valid
729 if (isset($aValidTokens[' '.$sToken])) {
730 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
731 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
733 isset($aValidTokens[$sToken])
734 && strpos($sToken, ' ') === false,
736 $iToken == 0 && $iPhrase == 0,
738 $iToken + 1 == sizeof($aWordset)
739 && $iPhrase + 1 == sizeof($aPhrases),
743 foreach ($aNewSearches as $oSearch) {
744 if ($oSearch->getRank() < $this->iMaxRank) {
745 $aNewWordsetSearches[] = $oSearch;
750 // Look for partial matches.
751 // Note that there is no point in adding country terms here
752 // because country is omitted in the address.
753 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
754 // Allow searching for a word - but at extra cost
755 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
756 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
760 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
763 foreach ($aNewSearches as $oSearch) {
764 if ($oSearch->getRank() < $this->iMaxRank) {
765 $aNewWordsetSearches[] = $oSearch;
772 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
773 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
775 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
777 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
778 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
780 $aSearchHash = array();
781 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
782 $sHash = serialize($aSearch);
783 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
784 else $aSearchHash[$sHash] = 1;
787 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
790 // Re-group the searches by their score, junk anything over 20 as just not worth trying
791 $aGroupedSearches = array();
792 foreach ($aNewPhraseSearches as $aSearch) {
793 $iRank = $aSearch->getRank();
794 if ($iRank < $this->iMaxRank) {
795 if (!isset($aGroupedSearches[$iRank])) {
796 $aGroupedSearches[$iRank] = array();
798 $aGroupedSearches[$iRank][] = $aSearch;
801 ksort($aGroupedSearches);
804 $aSearches = array();
805 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
806 $iSearchCount += sizeof($aNewSearches);
807 $aSearches = array_merge($aSearches, $aNewSearches);
808 if ($iSearchCount > 50) break;
811 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
814 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
815 $aGroupedSearches = array();
816 foreach ($aSearches as $oSearch) {
817 if (!$oSearch->isValidSearch()) {
821 $iRank = $oSearch->addToRank($iGlobalRank);
822 if (!isset($aGroupedSearches[$iRank])) {
823 $aGroupedSearches[$iRank] = array();
825 $aGroupedSearches[$iRank][] = $oSearch;
827 ksort($aGroupedSearches);
829 return $aGroupedSearches;
832 /* Perform the actual query lookup.
834 Returns an ordered list of results, each with the following fields:
835 osm_type: type of corresponding OSM object
839 P - postcode (internally computed)
840 osm_id: id of corresponding OSM object
841 class: general object class (corresponds to tag key of primary OSM tag)
842 type: subclass of object (corresponds to tag value of primary OSM tag)
843 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
844 rank_search: rank in search hierarchy
845 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
846 rank_address: rank in address hierarchy (determines orer in address)
847 place_id: internal key (may differ between different instances)
848 country_code: ISO country code
849 langaddress: localized full address
850 placename: localized name of object
851 ref: content of ref tag (if available)
854 importance: importance of place based on Wikipedia link count
855 addressimportance: cumulated importance of address elements
856 extra_place: type of place (for admin boundaries, if there is a place tag)
857 aBoundingBox: bounding Box
858 label: short description of the object class/type (English only)
859 name: full name (currently the same as langaddress)
860 foundorder: secondary ordering for places with same importance
864 public function lookup()
866 if (!$this->sQuery && !$this->aStructuredQuery) return array();
868 $oCtx = new SearchContext();
870 if ($this->aRoutePoints) {
871 $oCtx->setViewboxFromRoute(
875 $this->bBoundedSearch
877 } elseif ($this->aViewBox) {
878 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
880 if ($this->aExcludePlaceIDs) {
881 $oCtx->setExcludeList($this->aExcludePlaceIDs);
883 if ($this->aCountryCodes) {
884 $oCtx->setCountryList($this->aCountryCodes);
887 $sNormQuery = $this->normTerm($this->sQuery);
888 $sLanguagePrefArraySQL = getArraySQL(
889 array_map("getDBQuoted", $this->aLangPrefOrder)
892 $sQuery = $this->sQuery;
893 if (!preg_match('//u', $sQuery)) {
894 userError("Query string is not UTF-8 encoded.");
897 // Conflicts between US state abreviations and various words for 'the' in different languages
898 if (isset($this->aLangPrefOrder['name:en'])) {
899 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
900 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
901 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
904 // Do we have anything that looks like a lat/lon pair?
905 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
907 $aSearchResults = array();
908 if ($sQuery || $this->aStructuredQuery) {
909 // Start with a single blank search
910 $aSearches = array(new SearchDescription($oCtx));
913 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
919 '/\\[([\\w ]*)\\]/u',
924 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
925 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
926 if (!$sSpecialTerm) {
927 $sSpecialTerm = $aSpecialTerm[1];
931 if (!$sSpecialTerm && $this->aStructuredQuery
932 && isset($this->aStructuredQuery['amenity'])) {
933 $sSpecialTerm = $this->aStructuredQuery['amenity'];
934 unset($this->aStructuredQuery['amenity']);
937 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
938 $sSpecialTerm = pg_escape_string($sSpecialTerm);
940 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
941 "Cannot decode query. Wrong encoding?"
943 $sSQL = 'SELECT class, type FROM word ';
944 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
945 $sSQL .= ' AND class is not null AND class not in (\'place\')';
946 if (CONST_Debug) var_Dump($sSQL);
947 $aSearchWords = chksql($this->oDB->getAll($sSQL));
948 $aNewSearches = array();
949 foreach ($aSearches as $oSearch) {
950 foreach ($aSearchWords as $aSearchTerm) {
951 $oNewSearch = clone $oSearch;
952 $oNewSearch->setPoiSearch(
954 $aSearchTerm['class'],
957 $aNewSearches[] = $oNewSearch;
960 $aSearches = $aNewSearches;
963 // Split query into phrases
964 // Commas are used to reduce the search space by indicating where phrases split
965 if ($this->aStructuredQuery) {
966 $aInPhrases = $this->aStructuredQuery;
967 $bStructuredPhrases = true;
969 $aInPhrases = explode(',', $sQuery);
970 $bStructuredPhrases = false;
973 // Convert each phrase to standard form
974 // Create a list of standard words
975 // Get all 'sets' of words
976 // Generate a complete list of all
979 foreach ($aInPhrases as $iPhrase => $sPhrase) {
981 $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
982 "Cannot normalize query string (is it a UTF-8 string?)"
984 if (trim($sPhrase)) {
985 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
986 $oPhrase->addTokens($aTokens);
987 $aPhrases[] = $oPhrase;
991 if (sizeof($aTokens)) {
992 // Check which tokens we have, get the ID numbers
993 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
994 $sSQL .= ' FROM word ';
995 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
997 if (CONST_Debug) var_Dump($sSQL);
999 $aValidTokens = array();
1000 $aDatabaseWords = chksql(
1001 $this->oDB->getAll($sSQL),
1002 "Could not get word tokens."
1004 $aWordFrequencyScores = array();
1005 foreach ($aDatabaseWords as $aToken) {
1006 // Filter country tokens that do not match restricted countries.
1007 if ($this->aCountryCodes
1008 && $aToken['country_code']
1009 && !in_array($aToken['country_code'], $this->aCountryCodes)
1014 // Special terms need to appear in their normalized form.
1015 if ($aToken['word'] && $aToken['class']) {
1016 $sNormWord = $this->normTerm($aToken['word']);
1017 if (strpos($sNormQuery, $sNormWord) === false) {
1022 if (isset($aValidTokens[$aToken['word_token']])) {
1023 $aValidTokens[$aToken['word_token']][] = $aToken;
1025 $aValidTokens[$aToken['word_token']] = array($aToken);
1027 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1029 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1031 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1032 foreach ($aTokens as $sToken) {
1033 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1034 if (isset($aValidTokens[$aData[1]])) {
1035 foreach ($aValidTokens[$aData[1]] as $aToken) {
1036 if (!$aToken['class']) {
1037 if (isset($aValidTokens[$sToken])) {
1038 $aValidTokens[$sToken][] = $aToken;
1040 $aValidTokens[$sToken] = array($aToken);
1048 foreach ($aTokens as $sToken) {
1049 // Unknown single word token with a number - assume it is a house number
1050 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1051 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1055 // Any words that have failed completely?
1056 // TODO: suggestions
1058 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bStructuredPhrases);
1060 if ($this->bReverseInPlan) {
1061 // Reverse phrase array and also reverse the order of the wordsets in
1062 // the first and final phrase. Don't bother about phrases in the middle
1063 // because order in the address doesn't matter.
1064 $aPhrases = array_reverse($aPhrases);
1065 $aPhrases[0]->invertWordSets();
1066 if (sizeof($aPhrases) > 1) {
1067 $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
1069 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, false);
1071 foreach ($aGroupedSearches as $aSearches) {
1072 foreach ($aSearches as $aSearch) {
1073 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1074 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1076 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1080 $aGroupedSearches = $aReverseGroupedSearches;
1081 ksort($aGroupedSearches);
1084 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1085 $aGroupedSearches = array();
1086 foreach ($aSearches as $aSearch) {
1087 if ($aSearch->getRank() < $this->iMaxRank) {
1088 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1089 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1092 ksort($aGroupedSearches);
1095 // Filter out duplicate searches
1096 $aSearchHash = array();
1097 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1098 foreach ($aSearches as $iSearch => $aSearch) {
1099 $sHash = serialize($aSearch);
1100 if (isset($aSearchHash[$sHash])) {
1101 unset($aGroupedSearches[$iGroup][$iSearch]);
1102 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1104 $aSearchHash[$sHash] = 1;
1109 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1111 // Start the search process
1112 $aResults = array();
1115 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1117 foreach ($aSearches as $oSearch) {
1121 echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1122 _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1125 $aResults += $oSearch->query(
1127 $aWordFrequencyScores,
1128 $this->iMinAddressRank,
1129 $this->iMaxAddressRank,
1133 if ($iQueryLoop > 20) break;
1136 if (sizeof($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1137 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1138 // reduces the number of place ids, like a filter
1139 // rank_address is 30 for interpolated housenumbers
1140 $aFilterSql = array();
1141 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
1143 $sSQL = 'SELECT place_id FROM placex ';
1144 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
1146 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1147 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1148 $sSQL .= " OR (extratags->'place') = 'city'";
1150 if ($this->aAddressRankList) {
1151 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1154 $aFilterSql[] = $sSQL;
1156 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
1158 $sSQL = ' SELECT place_id FROM location_postcode lp ';
1159 $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
1160 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1161 if ($this->aAddressRankList) {
1162 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1165 $aFilterSql[] = $sSQL;
1168 $aFilteredIDs = array();
1170 $sSQL = join(' UNION ', $aFilterSql);
1171 if (CONST_Debug) var_dump($sSQL);
1172 $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
1176 foreach ($aResults as $oResult) {
1177 if (($this->iMaxAddressRank == 30 &&
1178 ($oResult->iTable == Result::TABLE_OSMLINE
1179 || $oResult->iTable == Result::TABLE_AUX
1180 || $oResult->iTable == Result::TABLE_TIGER))
1181 || in_array($oResult->iId, $aFilteredIDs)
1183 $tempIDs[$oResult->iId] = $oResult;
1186 $aResults = $tempIDs;
1189 if (sizeof($aResults)) break;
1190 if ($iGroupLoop > 4) break;
1191 if ($iQueryLoop > 30) break;
1194 $aSearchResults = $this->getDetails($aResults, $oCtx);
1196 // Just interpret as a reverse geocode
1197 $oReverse = new ReverseGeocode($this->oDB);
1198 $oReverse->setZoom(18);
1200 $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
1202 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1205 $aResults = array($oLookup->iId => $oLookup);
1206 $aSearchResults = $this->getDetails($aResults, $oCtx);
1208 $aSearchResults = array();
1213 if (!sizeof($aSearchResults)) {
1214 if ($this->bFallback) {
1215 if ($this->fallbackStructuredQuery()) {
1216 return $this->lookup();
1223 $aClassType = getClassTypesWithImportance();
1224 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1225 foreach ($aRecheckWords as $i => $sWord) {
1226 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1230 echo '<i>Recheck words:<\i>';
1231 var_dump($aRecheckWords);
1234 $oPlaceLookup = new PlaceLookup($this->oDB);
1235 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1236 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1237 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1238 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1239 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1240 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1242 foreach ($aSearchResults as $iResNum => $aResult) {
1244 $fDiameter = getResultDiameter($aResult);
1246 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1247 if ($aOutlineResult) {
1248 $aResult = array_merge($aResult, $aOutlineResult);
1251 if ($aResult['extra_place'] == 'city') {
1252 $aResult['class'] = 'place';
1253 $aResult['type'] = 'city';
1254 $aResult['rank_search'] = 16;
1257 // Is there an icon set for this type of result?
1258 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1259 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1261 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1264 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1265 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1267 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1268 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1269 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1271 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1273 // if tag '&addressdetails=1' is set in query
1274 if ($this->bIncludeAddressDetails) {
1275 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1276 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResults[$aResult['place_id']]->iHouseNumber);
1277 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1278 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1282 if ($this->bIncludeExtraTags) {
1283 if ($aResult['extra']) {
1284 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1286 $aResult['sExtraTags'] = (object) array();
1290 if ($this->bIncludeNameDetails) {
1291 if ($aResult['names']) {
1292 $aResult['sNameDetails'] = json_decode($aResult['names']);
1294 $aResult['sNameDetails'] = (object) array();
1298 $aResult['name'] = $aResult['langaddress'];
1300 if ($oCtx->hasNearPoint()) {
1301 $aResult['importance'] = 0.001;
1302 $aResult['foundorder'] = $aResult['addressimportance'];
1304 // Adjust importance for the number of exact string matches in the result
1305 $aResult['importance'] = max(0.001, $aResult['importance']);
1307 $sAddress = $aResult['langaddress'];
1308 foreach ($aRecheckWords as $i => $sWord) {
1309 if (stripos($sAddress, $sWord)!==false) {
1311 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1315 $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
1317 // secondary ordering (for results with same importance (the smaller the better):
1318 // - approximate importance of address parts
1319 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1320 // - number of exact matches from the query
1321 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
1322 // - importance of the class/type
1323 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1324 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1326 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1328 $aResult['foundorder'] += 0.01;
1331 if (CONST_Debug) var_dump($aResult);
1332 $aSearchResults[$iResNum] = $aResult;
1334 uasort($aSearchResults, 'byImportance');
1336 $aOSMIDDone = array();
1337 $aClassTypeNameDone = array();
1338 $aToFilter = $aSearchResults;
1339 $aSearchResults = array();
1342 foreach ($aToFilter as $iResNum => $aResult) {
1343 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1345 $fLat = $aResult['lat'];
1346 $fLon = $aResult['lon'];
1347 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1350 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1351 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1353 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1354 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1355 $aSearchResults[] = $aResult;
1358 // Absolute limit on number of results
1359 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1362 return $aSearchResults;