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, $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 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
751 foreach ($aNewSearches as $oSearch) {
752 if ($oSearch->getRank() < $this->iMaxRank) {
753 $aNewWordsetSearches[] = $oSearch;
760 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
761 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
763 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
765 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
766 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
768 $aSearchHash = array();
769 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
770 $sHash = serialize($aSearch);
771 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
772 else $aSearchHash[$sHash] = 1;
775 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
778 // Re-group the searches by their score, junk anything over 20 as just not worth trying
779 $aGroupedSearches = array();
780 foreach ($aNewPhraseSearches as $aSearch) {
781 $iRank = $aSearch->getRank();
782 if ($iRank < $this->iMaxRank) {
783 if (!isset($aGroupedSearches[$iRank])) {
784 $aGroupedSearches[$iRank] = array();
786 $aGroupedSearches[$iRank][] = $aSearch;
789 ksort($aGroupedSearches);
792 $aSearches = array();
793 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
794 $iSearchCount += sizeof($aNewSearches);
795 $aSearches = array_merge($aSearches, $aNewSearches);
796 if ($iSearchCount > 50) break;
799 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
802 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
803 $aGroupedSearches = array();
804 foreach ($aSearches as $oSearch) {
805 if (!$oSearch->isValidSearch($this->aCountryCodes)) {
809 $iRank = $oSearch->addToRank($iGlobalRank);
810 if (!isset($aGroupedSearches[$iRank])) {
811 $aGroupedSearches[$iRank] = array();
813 $aGroupedSearches[$iRank][] = $oSearch;
815 ksort($aGroupedSearches);
817 return $aGroupedSearches;
820 /* Perform the actual query lookup.
822 Returns an ordered list of results, each with the following fields:
823 osm_type: type of corresponding OSM object
827 P - postcode (internally computed)
828 osm_id: id of corresponding OSM object
829 class: general object class (corresponds to tag key of primary OSM tag)
830 type: subclass of object (corresponds to tag value of primary OSM tag)
831 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
832 rank_search: rank in search hierarchy
833 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
834 rank_address: rank in address hierarchy (determines orer in address)
835 place_id: internal key (may differ between different instances)
836 country_code: ISO country code
837 langaddress: localized full address
838 placename: localized name of object
839 ref: content of ref tag (if available)
842 importance: importance of place based on Wikipedia link count
843 addressimportance: cumulated importance of address elements
844 extra_place: type of place (for admin boundaries, if there is a place tag)
845 aBoundingBox: bounding Box
846 label: short description of the object class/type (English only)
847 name: full name (currently the same as langaddress)
848 foundorder: secondary ordering for places with same importance
852 public function lookup()
854 if (!$this->sQuery && !$this->aStructuredQuery) return array();
856 $oCtx = new SearchContext();
858 if ($this->aRoutePoints) {
859 $oCtx->setViewboxFromRoute(
863 $this->bBoundedSearch
865 } elseif ($this->aViewBox) {
866 $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
868 if ($this->aExcludePlaceIDs) {
869 $oCtx->setExcludeList($this->aExcludePlaceIDs);
871 if ($this->aCountryCodes) {
872 $oCtx->setCountryList($this->aCountryCodes);
875 $sNormQuery = $this->normTerm($this->sQuery);
876 $sLanguagePrefArraySQL = getArraySQL(
877 array_map("getDBQuoted", $this->aLangPrefOrder)
880 $sQuery = $this->sQuery;
881 if (!preg_match('//u', $sQuery)) {
882 userError("Query string is not UTF-8 encoded.");
885 // Conflicts between US state abreviations and various words for 'the' in different languages
886 if (isset($this->aLangPrefOrder['name:en'])) {
887 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
888 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
889 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
892 // Do we have anything that looks like a lat/lon pair?
893 $sQuery = $oCtx->setNearPointFromQuery($sQuery);
895 $aSearchResults = array();
896 if ($sQuery || $this->aStructuredQuery) {
897 // Start with a single blank search
898 $aSearches = array(new SearchDescription($oCtx));
901 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
907 '/\\[([\\w ]*)\\]/u',
912 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
913 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
914 if (!$sSpecialTerm) {
915 $sSpecialTerm = $aSpecialTerm[1];
919 if (!$sSpecialTerm && $this->aStructuredQuery
920 && isset($this->aStructuredQuery['amenity'])) {
921 $sSpecialTerm = $this->aStructuredQuery['amenity'];
922 unset($this->aStructuredQuery['amenity']);
925 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
926 $sSpecialTerm = pg_escape_string($sSpecialTerm);
928 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
929 "Cannot decode query. Wrong encoding?"
931 $sSQL = 'SELECT class, type FROM word ';
932 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
933 $sSQL .= ' AND class is not null AND class not in (\'place\')';
934 if (CONST_Debug) var_Dump($sSQL);
935 $aSearchWords = chksql($this->oDB->getAll($sSQL));
936 $aNewSearches = array();
937 foreach ($aSearches as $oSearch) {
938 foreach ($aSearchWords as $aSearchTerm) {
939 $oNewSearch = clone $oSearch;
940 $oNewSearch->setPoiSearch(
942 $aSearchTerm['class'],
945 $aNewSearches[] = $oNewSearch;
948 $aSearches = $aNewSearches;
951 // Split query into phrases
952 // Commas are used to reduce the search space by indicating where phrases split
953 if ($this->aStructuredQuery) {
954 $aInPhrases = $this->aStructuredQuery;
955 $bStructuredPhrases = true;
957 $aInPhrases = explode(',', $sQuery);
958 $bStructuredPhrases = false;
961 // Convert each phrase to standard form
962 // Create a list of standard words
963 // Get all 'sets' of words
964 // Generate a complete list of all
967 foreach ($aInPhrases as $iPhrase => $sPhrase) {
969 $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
970 "Cannot normalize query string (is it a UTF-8 string?)"
972 if (trim($sPhrase)) {
973 $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
974 $oPhrase->addTokens($aTokens);
975 $aPhrases[] = $oPhrase;
979 if (sizeof($aTokens)) {
980 // Check which tokens we have, get the ID numbers
981 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
982 $sSQL .= ' FROM word ';
983 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
985 if (CONST_Debug) var_Dump($sSQL);
987 $aValidTokens = array();
988 $aDatabaseWords = chksql(
989 $this->oDB->getAll($sSQL),
990 "Could not get word tokens."
992 $aWordFrequencyScores = array();
993 foreach ($aDatabaseWords as $aToken) {
994 // Very special case - require 2 letter country param to match the country code found
995 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
996 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1001 if (isset($aValidTokens[$aToken['word_token']])) {
1002 $aValidTokens[$aToken['word_token']][] = $aToken;
1004 $aValidTokens[$aToken['word_token']] = array($aToken);
1006 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1008 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1010 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1011 foreach ($aTokens as $sToken) {
1012 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1013 if (isset($aValidTokens[$aData[1]])) {
1014 foreach ($aValidTokens[$aData[1]] as $aToken) {
1015 if (!$aToken['class']) {
1016 if (isset($aValidTokens[$sToken])) {
1017 $aValidTokens[$sToken][] = $aToken;
1019 $aValidTokens[$sToken] = array($aToken);
1027 foreach ($aTokens as $sToken) {
1028 // Unknown single word token with a number - assume it is a house number
1029 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1030 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1034 // Any words that have failed completely?
1035 // TODO: suggestions
1037 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bStructuredPhrases, $sNormQuery);
1039 if ($this->bReverseInPlan) {
1040 // Reverse phrase array and also reverse the order of the wordsets in
1041 // the first and final phrase. Don't bother about phrases in the middle
1042 // because order in the address doesn't matter.
1043 $aPhrases = array_reverse($aPhrases);
1044 $aPhrases[0]->invertWordSets();
1045 if (sizeof($aPhrases) > 1) {
1046 $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
1048 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, false, $sNormQuery);
1050 foreach ($aGroupedSearches as $aSearches) {
1051 foreach ($aSearches as $aSearch) {
1052 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1053 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1055 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1059 $aGroupedSearches = $aReverseGroupedSearches;
1060 ksort($aGroupedSearches);
1063 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1064 $aGroupedSearches = array();
1065 foreach ($aSearches as $aSearch) {
1066 if ($aSearch->getRank() < $this->iMaxRank) {
1067 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1068 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1071 ksort($aGroupedSearches);
1074 // Filter out duplicate searches
1075 $aSearchHash = array();
1076 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1077 foreach ($aSearches as $iSearch => $aSearch) {
1078 $sHash = serialize($aSearch);
1079 if (isset($aSearchHash[$sHash])) {
1080 unset($aGroupedSearches[$iGroup][$iSearch]);
1081 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1083 $aSearchHash[$sHash] = 1;
1088 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1090 // Start the search process
1091 // array with: placeid => -1 | tiger-housenumber
1092 $aResultPlaceIDs = array();
1095 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1097 foreach ($aSearches as $oSearch) {
1101 echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1102 _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1105 $aRes = $oSearch->query(
1107 $aWordFrequencyScores,
1108 $this->exactMatchCache,
1109 $this->iMinAddressRank,
1110 $this->iMaxAddressRank,
1114 foreach ($aRes['IDs'] as $iPlaceID) {
1115 // array for placeID => -1 | Tiger housenumber
1116 $aResultPlaceIDs[$iPlaceID] = $aRes['houseNumber'];
1118 if ($iQueryLoop > 20) break;
1121 if (sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1122 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1123 // reduces the number of place ids, like a filter
1124 // rank_address is 30 for interpolated housenumbers
1125 $sWherePlaceId = 'WHERE place_id in (';
1126 $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1128 $sSQL = "SELECT place_id ";
1129 $sSQL .= "FROM placex ".$sWherePlaceId;
1131 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1132 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1133 $sSQL .= " OR (extratags->'place') = 'city'";
1135 if ($this->aAddressRankList) {
1136 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1138 $sSQL .= " ) UNION ";
1139 $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1140 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1141 if ($this->aAddressRankList) {
1142 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1145 if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1147 $sSQL .= " SELECT place_id ";
1148 $sSQL .= " FROM location_property_tiger ".$sWherePlaceId;
1150 if ($this->iMaxAddressRank == 30) {
1152 $sSQL .= " SELECT place_id ";
1153 $sSQL .= " FROM location_property_osmline ".$sWherePlaceId;
1155 if (CONST_Debug) var_dump($sSQL);
1156 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1158 foreach ($aFilteredPlaceIDs as $placeID) {
1159 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1161 $aResultPlaceIDs = $tempIDs;
1164 if (sizeof($aResultPlaceIDs)) break;
1165 if ($iGroupLoop > 4) break;
1166 if ($iQueryLoop > 30) break;
1169 // Did we find anything?
1170 if (sizeof($aResultPlaceIDs)) {
1171 $aSearchResults = $this->getDetails($aResultPlaceIDs, $oCtx);
1174 // Just interpret as a reverse geocode
1175 $oReverse = new ReverseGeocode($this->oDB);
1176 $oReverse->setZoom(18);
1178 $aLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
1180 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1182 if ($aLookup['place_id']) {
1183 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1), $oCtx);
1184 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1186 $aSearchResults = array();
1191 if (!sizeof($aSearchResults)) {
1192 if ($this->bFallback) {
1193 if ($this->fallbackStructuredQuery()) {
1194 return $this->lookup();
1201 $aClassType = getClassTypesWithImportance();
1202 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1203 foreach ($aRecheckWords as $i => $sWord) {
1204 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1208 echo '<i>Recheck words:<\i>';
1209 var_dump($aRecheckWords);
1212 $oPlaceLookup = new PlaceLookup($this->oDB);
1213 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1214 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1215 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1216 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1217 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1218 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1220 foreach ($aSearchResults as $iResNum => $aResult) {
1222 $fDiameter = getResultDiameter($aResult);
1224 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1225 if ($aOutlineResult) {
1226 $aResult = array_merge($aResult, $aOutlineResult);
1229 if ($aResult['extra_place'] == 'city') {
1230 $aResult['class'] = 'place';
1231 $aResult['type'] = 'city';
1232 $aResult['rank_search'] = 16;
1235 // Is there an icon set for this type of result?
1236 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1237 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1239 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1242 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1243 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1245 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1246 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1247 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1249 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1251 // if tag '&addressdetails=1' is set in query
1252 if ($this->bIncludeAddressDetails) {
1253 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1254 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1255 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1256 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1260 if ($this->bIncludeExtraTags) {
1261 if ($aResult['extra']) {
1262 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1264 $aResult['sExtraTags'] = (object) array();
1268 if ($this->bIncludeNameDetails) {
1269 if ($aResult['names']) {
1270 $aResult['sNameDetails'] = json_decode($aResult['names']);
1272 $aResult['sNameDetails'] = (object) array();
1276 $aResult['name'] = $aResult['langaddress'];
1278 if ($oCtx->hasNearPoint())
1280 $aResult['importance'] = 0.001;
1281 $aResult['foundorder'] = $aResult['addressimportance'];
1283 // Adjust importance for the number of exact string matches in the result
1284 $aResult['importance'] = max(0.001, $aResult['importance']);
1286 $sAddress = $aResult['langaddress'];
1287 foreach ($aRecheckWords as $i => $sWord) {
1288 if (stripos($sAddress, $sWord)!==false) {
1290 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1294 $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
1296 // secondary ordering (for results with same importance (the smaller the better):
1297 // - approximate importance of address parts
1298 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1299 // - number of exact matches from the query
1300 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1301 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1302 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1303 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1305 // - importance of the class/type
1306 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1307 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1309 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1311 $aResult['foundorder'] += 0.01;
1314 if (CONST_Debug) var_dump($aResult);
1315 $aSearchResults[$iResNum] = $aResult;
1317 uasort($aSearchResults, 'byImportance');
1319 $aOSMIDDone = array();
1320 $aClassTypeNameDone = array();
1321 $aToFilter = $aSearchResults;
1322 $aSearchResults = array();
1325 foreach ($aToFilter as $iResNum => $aResult) {
1326 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1328 $fLat = $aResult['lat'];
1329 $fLon = $aResult['lon'];
1330 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1333 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1334 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1336 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1337 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1338 $aSearchResults[] = $aResult;
1341 // Absolute limit on number of results
1342 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1345 return $aSearchResults;