5 require_once(CONST_BasePath.'/lib/NearPoint.php');
6 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
8 require_once(CONST_BasePath.'/lib/SearchDescription.php');
14 protected $aLangPrefOrder = array();
16 protected $bIncludeAddressDetails = false;
17 protected $bIncludeExtraTags = false;
18 protected $bIncludeNameDetails = false;
20 protected $bIncludePolygonAsPoints = false;
21 protected $bIncludePolygonAsText = false;
22 protected $bIncludePolygonAsGeoJSON = false;
23 protected $bIncludePolygonAsKML = false;
24 protected $bIncludePolygonAsSVG = false;
25 protected $fPolygonSimplificationThreshold = 0.0;
27 protected $aExcludePlaceIDs = array();
28 protected $bDeDupe = true;
29 protected $bReverseInPlan = false;
31 protected $iLimit = 20;
32 protected $iFinalLimit = 10;
33 protected $iOffset = 0;
34 protected $bFallback = false;
36 protected $aCountryCodes = false;
38 protected $bBoundedSearch = false;
39 protected $aViewBox = false;
40 protected $sViewboxCentreSQL = false;
41 protected $sViewboxSmallSQL = false;
42 protected $sViewboxLargeSQL = 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 setRoute($aRoutePoints, $fRouteWidth)
189 $this->aViewBox = false;
191 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
193 foreach ($aRoutePoints as $aPoint) {
194 $fPoint = (float)$aPoint;
195 $this->sViewboxCentreSQL .= $sSep.$fPoint;
196 $sSep = ($sSep == ' ') ? ',' : ' ';
198 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
200 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
201 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
203 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
204 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
207 public function setViewbox($aViewbox)
209 $this->aViewBox = array_map('floatval', $aViewbox);
211 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
212 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
213 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
214 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
216 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
217 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
219 userError("Bad parameter 'viewbox'. Not a box.");
222 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
223 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
224 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
225 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
226 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
227 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
229 $this->sViewboxCentreSQL = false;
230 $this->sViewboxSmallSQL = sprintf(
231 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
237 $this->sViewboxLargeSQL = sprintf(
238 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
246 public function setQuery($sQueryString)
248 $this->sQuery = $sQueryString;
249 $this->aStructuredQuery = false;
252 public function getQueryString()
254 return $this->sQuery;
258 public function loadParamArray($oParams)
260 $this->bIncludeAddressDetails
261 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
262 $this->bIncludeExtraTags
263 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
264 $this->bIncludeNameDetails
265 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
267 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
268 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
270 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
271 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
273 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
275 // List of excluded Place IDs - used for more acurate pageing
276 $sExcluded = $oParams->getStringList('exclude_place_ids');
278 foreach ($sExcluded as $iExcludedPlaceID) {
279 $iExcludedPlaceID = (int)$iExcludedPlaceID;
280 if ($iExcludedPlaceID)
281 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
284 if (isset($aExcludePlaceIDs))
285 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
288 // Only certain ranks of feature
289 $sFeatureType = $oParams->getString('featureType');
290 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
291 if ($sFeatureType) $this->setFeatureType($sFeatureType);
294 $sCountries = $oParams->getStringList('countrycodes');
296 foreach ($sCountries as $sCountryCode) {
297 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
298 $aCountries[] = strtolower($sCountryCode);
301 if (isset($aCountries))
302 $this->aCountryCodes = $aCountries;
305 $aViewbox = $oParams->getStringList('viewboxlbrt');
307 if (count($aViewbox) != 4) {
308 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
310 $this->setViewbox($aViewbox);
312 $aViewbox = $oParams->getStringList('viewbox');
314 if (count($aViewbox) != 4) {
315 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
317 $this->setViewBox($aViewbox);
319 $aRoute = $oParams->getStringList('route');
320 $fRouteWidth = $oParams->getFloat('routewidth');
321 if ($aRoute && $fRouteWidth) {
322 $this->setRoute($aRoute, $fRouteWidth);
328 public function setQueryFromParams($oParams)
331 $sQuery = $oParams->getString('q');
333 $this->setStructuredQuery(
334 $oParams->getString('amenity'),
335 $oParams->getString('street'),
336 $oParams->getString('city'),
337 $oParams->getString('county'),
338 $oParams->getString('state'),
339 $oParams->getString('country'),
340 $oParams->getString('postalcode')
342 $this->setReverseInPlan(false);
344 $this->setQuery($sQuery);
348 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
350 $sValue = trim($sValue);
351 if (!$sValue) return false;
352 $this->aStructuredQuery[$sKey] = $sValue;
353 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
354 $this->iMinAddressRank = $iNewMinAddressRank;
355 $this->iMaxAddressRank = $iNewMaxAddressRank;
357 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
361 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
363 $this->sQuery = false;
366 $this->iMinAddressRank = 0;
367 $this->iMaxAddressRank = 30;
368 $this->aAddressRankList = array();
370 $this->aStructuredQuery = array();
371 $this->sAllowedTypesSQLList = False;
373 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
374 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
375 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
376 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
377 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
378 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
379 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
381 if (sizeof($this->aStructuredQuery) > 0) {
382 $this->sQuery = join(', ', $this->aStructuredQuery);
383 if ($this->iMaxAddressRank < 30) {
384 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
389 public function fallbackStructuredQuery()
391 if (!$this->aStructuredQuery) return false;
393 $aParams = $this->aStructuredQuery;
395 if (sizeof($aParams) == 1) return false;
397 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
399 foreach ($aOrderToFallback as $sType) {
400 if (isset($aParams[$sType])) {
401 unset($aParams[$sType]);
402 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
410 public function getDetails($aPlaceIDs)
412 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
413 if (sizeof($aPlaceIDs) == 0) return array();
415 $sLanguagePrefArraySQL = getArraySQL(
416 array_map("getDBQuoted",
417 $this->aLangPrefOrder)
420 // Get the details for display (is this a redundant extra step?)
421 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
423 $sImportanceSQL = '';
424 $sImportanceSQLGeom = '';
425 if ($this->sViewboxSmallSQL) {
426 $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
427 $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, geometry) THEN 1 ELSE 0.75 END * ";
429 if ($this->sViewboxLargeSQL) {
430 $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
431 $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, geometry) THEN 1 ELSE 0.75 END * ";
435 $sSQL .= " osm_type,";
439 $sSQL .= " admin_level,";
440 $sSQL .= " rank_search,";
441 $sSQL .= " rank_address,";
442 $sSQL .= " min(place_id) AS place_id, ";
443 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
444 $sSQL .= " country_code, ";
445 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
446 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
447 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
448 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
449 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
450 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
451 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
452 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
454 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
456 $sSQL .= " place_addressline s, ";
457 $sSQL .= " placex p";
458 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
459 $sSQL .= " AND p.place_id = s.address_place_id ";
460 $sSQL .= " AND s.isaddress ";
461 $sSQL .= " AND p.importance is not null ";
462 $sSQL .= " ) AS addressimportance, ";
463 $sSQL .= " (extratags->'place') AS extra_place ";
464 $sSQL .= " FROM placex";
465 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
467 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
468 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
469 $sSQL .= " OR (extratags->'place') = 'city'";
471 if ($this->aAddressRankList) {
472 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
475 if ($this->sAllowedTypesSQLList) {
476 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
478 $sSQL .= " AND linked_place_id is null ";
479 $sSQL .= " GROUP BY ";
480 $sSQL .= " osm_type, ";
481 $sSQL .= " osm_id, ";
484 $sSQL .= " admin_level, ";
485 $sSQL .= " rank_search, ";
486 $sSQL .= " rank_address, ";
487 $sSQL .= " country_code, ";
488 $sSQL .= " importance, ";
489 if (!$this->bDeDupe) $sSQL .= "place_id,";
490 $sSQL .= " langaddress, ";
491 $sSQL .= " placename, ";
493 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
494 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
495 $sSQL .= " extratags->'place' ";
500 $sSQL .= " 'P' as osm_type,";
501 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
502 $sSQL .= " 'place' as class, 'postcode' as type,";
503 $sSQL .= " null as admin_level, rank_search, rank_address,";
504 $sSQL .= " place_id, parent_place_id, country_code,";
505 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
506 $sSQL .= " postcode as placename,";
507 $sSQL .= " postcode as ref,";
508 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
509 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
510 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
511 $sSQL .= $sImportanceSQLGeom."(0.75-(rank_search::float/40)) AS importance, ";
513 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
515 $sSQL .= " place_addressline s, ";
516 $sSQL .= " placex p";
517 $sSQL .= " WHERE s.place_id = lp.parent_place_id";
518 $sSQL .= " AND p.place_id = s.address_place_id ";
519 $sSQL .= " AND s.isaddress";
520 $sSQL .= " AND p.importance is not null";
521 $sSQL .= " ) AS addressimportance, ";
522 $sSQL .= " null AS extra_place ";
523 $sSQL .= "FROM location_postcode lp";
524 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
526 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
527 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
528 // with start- and endnumber, the common osm housenumbers are usually saved as points
531 $length = count($aPlaceIDs);
532 foreach ($aPlaceIDs as $placeID => $housenumber) {
534 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
535 if ($i<$length) $sHousenumbers .= ", ";
538 if (CONST_Use_US_Tiger_Data) {
539 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
542 $sSQL .= " 'T' AS osm_type, ";
543 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
544 $sSQL .= " 'place' AS class, ";
545 $sSQL .= " 'house' AS type, ";
546 $sSQL .= " null AS admin_level, ";
547 $sSQL .= " 30 AS rank_search, ";
548 $sSQL .= " 30 AS rank_address, ";
549 $sSQL .= " min(place_id) AS place_id, ";
550 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
551 $sSQL .= " 'us' AS country_code, ";
552 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
553 $sSQL .= " null AS placename, ";
554 $sSQL .= " null AS ref, ";
555 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
556 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
557 $sSQL .= " avg(st_x(centroid)) AS lon, ";
558 $sSQL .= " avg(st_y(centroid)) AS lat,";
559 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
561 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
563 $sSQL .= " place_addressline s, ";
564 $sSQL .= " placex p";
565 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
566 $sSQL .= " AND p.place_id = s.address_place_id ";
567 $sSQL .= " AND s.isaddress";
568 $sSQL .= " AND p.importance is not null";
569 $sSQL .= " ) AS addressimportance, ";
570 $sSQL .= " null AS extra_place ";
572 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
573 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
574 $sSQL .= " parent_place_id, ";
575 $sSQL .= " housenumber_for_place";
577 $sSQL .= " location_property_tiger ";
578 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
580 $sSQL .= " housenumber_for_place>=0";
581 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
582 $sSQL .= " ) AS blub"; //postgres wants an alias here
583 $sSQL .= " GROUP BY";
584 $sSQL .= " place_id, ";
585 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
586 if (!$this->bDeDupe) $sSQL .= ", place_id ";
589 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
592 $sSQL .= " 'W' AS osm_type, ";
593 $sSQL .= " osm_id, ";
594 $sSQL .= " 'place' AS class, ";
595 $sSQL .= " 'house' AS type, ";
596 $sSQL .= " null AS admin_level, ";
597 $sSQL .= " 30 AS rank_search, ";
598 $sSQL .= " 30 AS rank_address, ";
599 $sSQL .= " min(place_id) as place_id, ";
600 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
601 $sSQL .= " country_code, ";
602 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
603 $sSQL .= " null AS placename, ";
604 $sSQL .= " null AS ref, ";
605 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
606 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
607 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
608 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
609 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
612 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
614 $sSQL .= " place_addressline s, ";
615 $sSQL .= " placex p";
616 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
617 $sSQL .= " AND p.place_id = s.address_place_id ";
618 $sSQL .= " AND s.isaddress ";
619 $sSQL .= " AND p.importance is not null";
620 $sSQL .= " ) AS addressimportance,";
621 $sSQL .= " null AS extra_place ";
624 $sSQL .= " osm_id, ";
625 $sSQL .= " place_id, ";
626 $sSQL .= " country_code, ";
627 $sSQL .= " CASE "; // interpolate the housenumbers here
628 $sSQL .= " WHEN startnumber != endnumber ";
629 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
630 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
631 $sSQL .= " END as centroid, ";
632 $sSQL .= " parent_place_id, ";
633 $sSQL .= " housenumber_for_place ";
635 $sSQL .= " location_property_osmline ";
636 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
638 $sSQL .= " WHERE housenumber_for_place>=0 ";
639 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
640 $sSQL .= " ) as blub"; //postgres wants an alias here
641 $sSQL .= " GROUP BY ";
642 $sSQL .= " osm_id, ";
643 $sSQL .= " place_id, ";
644 $sSQL .= " housenumber_for_place, ";
645 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
646 if (!$this->bDeDupe) $sSQL .= ", place_id ";
648 if (CONST_Use_Aux_Location_data) {
651 $sSQL .= " 'L' AS osm_type, ";
652 $sSQL .= " place_id AS osm_id, ";
653 $sSQL .= " 'place' AS class,";
654 $sSQL .= " 'house' AS type, ";
655 $sSQL .= " null AS admin_level, ";
656 $sSQL .= " 0 AS rank_search,";
657 $sSQL .= " 0 AS rank_address, ";
658 $sSQL .= " min(place_id) AS place_id,";
659 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
660 $sSQL .= " 'us' AS country_code, ";
661 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
662 $sSQL .= " null AS placename, ";
663 $sSQL .= " null AS ref, ";
664 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
665 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
666 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
667 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
668 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
670 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
672 $sSQL .= " place_addressline s, ";
673 $sSQL .= " placex p";
674 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
675 $sSQL .= " AND p.place_id = s.address_place_id ";
676 $sSQL .= " AND s.isaddress";
677 $sSQL .= " AND p.importance is not null";
678 $sSQL .= " ) AS addressimportance, ";
679 $sSQL .= " null AS extra_place ";
680 $sSQL .= " FROM location_property_aux ";
681 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
682 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
683 $sSQL .= " GROUP BY ";
684 $sSQL .= " place_id, ";
685 if (!$this->bDeDupe) $sSQL .= "place_id, ";
686 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
690 $sSQL .= " order by importance desc";
695 $aSearchResults = chksql(
696 $this->oDB->getAll($sSQL),
697 "Could not get details for place."
700 return $aSearchResults;
703 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
706 Calculate all searches using aValidTokens i.e.
707 'Wodsworth Road, Sheffield' =>
711 0 1 (wodsworth)(road)
714 Score how good the search is so they can be ordered
718 foreach ($aPhrases as $iPhrase => $aPhrase) {
719 $aNewPhraseSearches = array();
720 if ($bStructuredPhrases) {
721 $sPhraseType = $aPhraseTypes[$iPhrase];
726 foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
727 // Too many permutations - too expensive
728 if ($iWordSet > 120) break;
730 $aWordsetSearches = $aSearches;
732 // Add all words from this wordset
733 foreach ($aWordset as $iToken => $sToken) {
734 //echo "<br><b>$sToken</b>";
735 $aNewWordsetSearches = array();
737 foreach ($aWordsetSearches as $oCurrentSearch) {
739 //var_dump($oCurrentSearch);
742 // If the token is valid
743 if (isset($aValidTokens[' '.$sToken])) {
744 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
745 // Recheck if the original word shows up in the query.
746 $bWordInQuery = false;
747 if (isset($aSearchTerm['word']) && $aSearchTerm['word']) {
748 $bWordInQuery = strpos(
750 $this->normTerm($aSearchTerm['word'])
753 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
756 isset($aValidTokens[$sToken])
757 && strpos($sToken, ' ') === false,
759 $iToken == 0 && $iPhrase == 0,
761 $iToken + 1 == sizeof($aWordset)
762 && $iPhrase + 1 == sizeof($aPhrases),
766 foreach ($aNewSearches as $oSearch) {
767 if ($oSearch->getRank() < $this->iMaxRank) {
768 $aNewWordsetSearches[] = $oSearch;
773 // Look for partial matches.
774 // Note that there is no point in adding country terms here
775 // because country is omitted in the address.
776 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
777 // Allow searching for a word - but at extra cost
778 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
779 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
783 $aWordFrequencyScores,
784 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
787 foreach ($aNewSearches as $oSearch) {
788 if ($oSearch->getRank() < $this->iMaxRank) {
789 $aNewWordsetSearches[] = $oSearch;
797 usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
798 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
800 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
802 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
803 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
805 $aSearchHash = array();
806 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
807 $sHash = serialize($aSearch);
808 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
809 else $aSearchHash[$sHash] = 1;
812 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
815 // Re-group the searches by their score, junk anything over 20 as just not worth trying
816 $aGroupedSearches = array();
817 foreach ($aNewPhraseSearches as $aSearch) {
818 $iRank = $aSearch->getRank();
819 if ($iRank < $this->iMaxRank) {
820 if (!isset($aGroupedSearches[$iRank])) {
821 $aGroupedSearches[$iRank] = array();
823 $aGroupedSearches[$iRank][] = $aSearch;
826 ksort($aGroupedSearches);
829 $aSearches = array();
830 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
831 $iSearchCount += sizeof($aNewSearches);
832 $aSearches = array_merge($aSearches, $aNewSearches);
833 if ($iSearchCount > 50) break;
836 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
839 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
840 $aGroupedSearches = array();
841 foreach ($aSearches as $oSearch) {
842 if (!$oSearch->isValidSearch($this->aCountryCodes)) {
846 $iRank = $oSearch->addToRank($iGlobalRank);
847 if (!isset($aGroupedSearches[$iRank])) {
848 $aGroupedSearches[$iRank] = array();
850 $aGroupedSearches[$iRank][] = $oSearch;
852 ksort($aGroupedSearches);
854 return $aGroupedSearches;
857 /* Perform the actual query lookup.
859 Returns an ordered list of results, each with the following fields:
860 osm_type: type of corresponding OSM object
864 P - postcode (internally computed)
865 osm_id: id of corresponding OSM object
866 class: general object class (corresponds to tag key of primary OSM tag)
867 type: subclass of object (corresponds to tag value of primary OSM tag)
868 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
869 rank_search: rank in search hierarchy
870 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
871 rank_address: rank in address hierarchy (determines orer in address)
872 place_id: internal key (may differ between different instances)
873 country_code: ISO country code
874 langaddress: localized full address
875 placename: localized name of object
876 ref: content of ref tag (if available)
879 importance: importance of place based on Wikipedia link count
880 addressimportance: cumulated importance of address elements
881 extra_place: type of place (for admin boundaries, if there is a place tag)
882 aBoundingBox: bounding Box
883 label: short description of the object class/type (English only)
884 name: full name (currently the same as langaddress)
885 foundorder: secondary ordering for places with same importance
889 public function lookup()
891 if (!$this->sQuery && !$this->aStructuredQuery) return array();
893 $sNormQuery = $this->normTerm($this->sQuery);
894 $sLanguagePrefArraySQL = getArraySQL(
895 array_map("getDBQuoted",
896 $this->aLangPrefOrder)
898 $sCountryCodesSQL = false;
899 if ($this->aCountryCodes) {
900 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
903 $sQuery = $this->sQuery;
904 if (!preg_match('//u', $sQuery)) {
905 userError("Query string is not UTF-8 encoded.");
908 // Conflicts between US state abreviations and various words for 'the' in different languages
909 if (isset($this->aLangPrefOrder['name:en'])) {
910 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
911 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
912 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
915 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
916 if ($this->sViewboxCentreSQL) {
917 // For complex viewboxes (routes) precompute the bounding geometry
919 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
920 "Could not get small viewbox"
922 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
925 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
926 "Could not get large viewbox"
928 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
931 // Do we have anything that looks like a lat/lon pair?
933 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
934 $oNearPoint = $aLooksLike['pt'];
935 $sQuery = $aLooksLike['query'];
938 $aSearchResults = array();
939 if ($sQuery || $this->aStructuredQuery) {
940 // Start with a single blank search
941 $aSearches = array(new SearchDescription());
944 $aSearches[0]->setNear($oNearPoint);
948 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
954 '/\\[([\\w ]*)\\]/u',
959 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
960 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
961 if (!$sSpecialTerm) {
962 $sSpecialTerm = $aSpecialTerm[1];
966 if (!$sSpecialTerm && $this->aStructuredQuery
967 && isset($this->aStructuredQuery['amenity'])) {
968 $sSpecialTerm = $this->aStructuredQuery['amenity'];
969 unset($this->aStructuredQuery['amenity']);
972 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
973 $sSpecialTerm = pg_escape_string($sSpecialTerm);
975 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
976 "Cannot decode query. Wrong encoding?"
978 $sSQL = 'SELECT class, type FROM word ';
979 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
980 $sSQL .= ' AND class is not null AND class not in (\'place\')';
981 if (CONST_Debug) var_Dump($sSQL);
982 $aSearchWords = chksql($this->oDB->getAll($sSQL));
983 $aNewSearches = array();
984 foreach ($aSearches as $oSearch) {
985 foreach ($aSearchWords as $aSearchTerm) {
986 $oNewSearch = clone $oSearch;
987 $oNewSearch->setPoiSearch(
989 $aSearchTerm['class'],
992 $aNewSearches[] = $oNewSearch;
995 $aSearches = $aNewSearches;
998 // Split query into phrases
999 // Commas are used to reduce the search space by indicating where phrases split
1000 if ($this->aStructuredQuery) {
1001 $aPhrases = $this->aStructuredQuery;
1002 $bStructuredPhrases = true;
1004 $aPhrases = explode(',', $sQuery);
1005 $bStructuredPhrases = false;
1008 // Convert each phrase to standard form
1009 // Create a list of standard words
1010 // Get all 'sets' of words
1011 // Generate a complete list of all
1013 foreach ($aPhrases as $iPhrase => $sPhrase) {
1015 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1016 "Cannot normalize query string (is it a UTF-8 string?)"
1018 if (trim($aPhrase['string'])) {
1019 $aPhrases[$iPhrase] = $aPhrase;
1020 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1021 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1022 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1024 unset($aPhrases[$iPhrase]);
1028 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1029 $aPhraseTypes = array_keys($aPhrases);
1030 $aPhrases = array_values($aPhrases);
1032 if (sizeof($aTokens)) {
1033 // Check which tokens we have, get the ID numbers
1034 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1035 $sSQL .= ' FROM word ';
1036 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1038 if (CONST_Debug) var_Dump($sSQL);
1040 $aValidTokens = array();
1041 $aDatabaseWords = chksql(
1042 $this->oDB->getAll($sSQL),
1043 "Could not get word tokens."
1045 $aPossibleMainWordIDs = array();
1046 $aWordFrequencyScores = array();
1047 foreach ($aDatabaseWords as $aToken) {
1048 // Very special case - require 2 letter country param to match the country code found
1049 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1050 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1055 if (isset($aValidTokens[$aToken['word_token']])) {
1056 $aValidTokens[$aToken['word_token']][] = $aToken;
1058 $aValidTokens[$aToken['word_token']] = array($aToken);
1060 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1061 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1063 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1065 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1066 foreach ($aTokens as $sToken) {
1067 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1068 if (isset($aValidTokens[$aData[1]])) {
1069 foreach ($aValidTokens[$aData[1]] as $aToken) {
1070 if (!$aToken['class']) {
1071 if (isset($aValidTokens[$sToken])) {
1072 $aValidTokens[$sToken][] = $aToken;
1074 $aValidTokens[$sToken] = array($aToken);
1082 foreach ($aTokens as $sToken) {
1083 // Unknown single word token with a number - assume it is a house number
1084 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1085 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1089 // Any words that have failed completely?
1090 // TODO: suggestions
1092 // Start the search process
1093 // array with: placeid => -1 | tiger-housenumber
1094 $aResultPlaceIDs = array();
1096 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1098 if ($this->bReverseInPlan) {
1099 // Reverse phrase array and also reverse the order of the wordsets in
1100 // the first and final phrase. Don't bother about phrases in the middle
1101 // because order in the address doesn't matter.
1102 $aPhrases = array_reverse($aPhrases);
1103 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1104 if (sizeof($aPhrases) > 1) {
1105 $aFinalPhrase = end($aPhrases);
1106 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1108 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1110 foreach ($aGroupedSearches as $aSearches) {
1111 foreach ($aSearches as $aSearch) {
1112 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1113 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1115 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1119 $aGroupedSearches = $aReverseGroupedSearches;
1120 ksort($aGroupedSearches);
1123 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1124 $aGroupedSearches = array();
1125 foreach ($aSearches as $aSearch) {
1126 if ($aSearch->getRank() < $this->iMaxRank) {
1127 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1128 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1131 ksort($aGroupedSearches);
1134 // Filter out duplicate searches
1135 $aSearchHash = array();
1136 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1137 foreach ($aSearches as $iSearch => $aSearch) {
1138 $sHash = serialize($aSearch);
1139 if (isset($aSearchHash[$sHash])) {
1140 unset($aGroupedSearches[$iGroup][$iSearch]);
1141 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1143 $aSearchHash[$sHash] = 1;
1148 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1152 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1154 foreach ($aSearches as $oSearch) {
1156 $searchedHousenumber = -1;
1158 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1159 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1161 $aPlaceIDs = array();
1162 if ($oSearch->isCountrySearch()) {
1163 // Just looking for a country - look it up
1164 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1165 $aPlaceIDs = $oSearch->queryCountry(
1167 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : ''
1170 } elseif (!$oSearch->isNamedSearch()) {
1171 // looking for a POI in a geographic area
1172 if (!$bBoundingBoxSearch && !$oSearch->isNearSearch()) {
1176 $aPlaceIDs = $oSearch->queryNearbyPoi(
1179 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
1180 $this->sViewboxCentreSQL,
1181 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1184 } elseif ($oSearch->isOperator(Operator::POSTCODE)) {
1185 $aPlaceIDs = $oSearch->queryPostcode(
1192 // First search for places according to name and address.
1193 $aNamedPlaceIDs = $oSearch->queryNamedPlace(
1195 $aWordFrequencyScores,
1197 $this->iMinAddressRank,
1198 $this->iMaxAddressRank,
1199 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1200 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
1201 $bBoundingBoxSearch ? $this->sViewboxLargeSQL : '',
1205 if (sizeof($aNamedPlaceIDs)) {
1206 foreach ($aNamedPlaceIDs as $aRow) {
1207 $aPlaceIDs[] = $aRow['place_id'];
1208 $this->exactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
1212 //now search for housenumber, if housenumber provided
1213 if ($oSearch->hasHouseNumber() && sizeof($aPlaceIDs)) {
1214 $aResult = $oSearch->queryHouseNumber(
1217 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1221 if (sizeof($aResult)) {
1222 $searchedHousenumber = $aResult['iHouseNumber'];
1223 $aPlaceIDs = $aResult['aPlaceIDs'];
1224 } elseif (!$oSearch->looksLikeFullAddress()) {
1225 $aPlaceIDs = array();
1229 // finally get POIs if requested
1230 if ($oSearch->isPoiSearch() && sizeof($aPlaceIDs)) {
1231 $aPlaceIDs = $oSearch->queryPoiByOperator(
1234 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1241 echo "<br><b>Place IDs:</b> ";
1242 var_Dump($aPlaceIDs);
1245 if (sizeof($aPlaceIDs) && $oSearch->getPostcode()) {
1246 $sSQL = 'SELECT place_id FROM placex';
1247 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
1248 $sSQL .= " AND postcode = '".$oSearch->getPostcode()."'";
1249 if (CONST_Debug) var_dump($sSQL);
1250 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1251 if ($aFilteredPlaceIDs) {
1252 $aPlaceIDs = $aFilteredPlaceIDs;
1254 echo "<br><b>Place IDs after postcode filtering:</b> ";
1255 var_Dump($aPlaceIDs);
1260 foreach ($aPlaceIDs as $iPlaceID) {
1261 // array for placeID => -1 | Tiger housenumber
1262 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1264 if ($iQueryLoop > 20) break;
1267 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1268 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1269 // reduces the number of place ids, like a filter
1270 // rank_address is 30 for interpolated housenumbers
1271 $sWherePlaceId = 'WHERE place_id in (';
1272 $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1274 $sSQL = "SELECT place_id ";
1275 $sSQL .= "FROM placex ".$sWherePlaceId;
1277 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1278 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1279 $sSQL .= " OR (extratags->'place') = 'city'";
1281 if ($this->aAddressRankList) {
1282 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1284 $sSQL .= " ) UNION ";
1285 $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1286 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1287 if ($this->aAddressRankList) {
1288 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1291 if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1293 $sSQL .= " SELECT place_id ";
1294 $sSQL .= " FROM location_property_tiger ".$sWherePlaceId;
1296 if ($this->iMaxAddressRank == 30) {
1298 $sSQL .= " SELECT place_id ";
1299 $sSQL .= " FROM location_property_osmline ".$sWherePlaceId;
1301 if (CONST_Debug) var_dump($sSQL);
1302 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1304 foreach ($aFilteredPlaceIDs as $placeID) {
1305 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1307 $aResultPlaceIDs = $tempIDs;
1311 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1312 if ($iGroupLoop > 4) break;
1313 if ($iQueryLoop > 30) break;
1316 // Did we find anything?
1317 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1318 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1321 // Just interpret as a reverse geocode
1322 $oReverse = new ReverseGeocode($this->oDB);
1323 $oReverse->setZoom(18);
1325 $aLookup = $oReverse->lookup(
1331 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1333 if ($aLookup['place_id']) {
1334 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1335 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1337 $aSearchResults = array();
1342 if (!sizeof($aSearchResults)) {
1343 if ($this->bFallback) {
1344 if ($this->fallbackStructuredQuery()) {
1345 return $this->lookup();
1352 $aClassType = getClassTypesWithImportance();
1353 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1354 foreach ($aRecheckWords as $i => $sWord) {
1355 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1359 echo '<i>Recheck words:<\i>';
1360 var_dump($aRecheckWords);
1363 $oPlaceLookup = new PlaceLookup($this->oDB);
1364 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1365 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1366 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1367 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1368 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1369 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1371 foreach ($aSearchResults as $iResNum => $aResult) {
1373 $fDiameter = getResultDiameter($aResult);
1375 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1376 if ($aOutlineResult) {
1377 $aResult = array_merge($aResult, $aOutlineResult);
1380 if ($aResult['extra_place'] == 'city') {
1381 $aResult['class'] = 'place';
1382 $aResult['type'] = 'city';
1383 $aResult['rank_search'] = 16;
1386 // Is there an icon set for this type of result?
1387 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1388 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1390 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1393 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1394 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1396 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1397 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1398 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1400 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1402 // if tag '&addressdetails=1' is set in query
1403 if ($this->bIncludeAddressDetails) {
1404 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1405 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1406 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1407 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1411 if ($this->bIncludeExtraTags) {
1412 if ($aResult['extra']) {
1413 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1415 $aResult['sExtraTags'] = (object) array();
1419 if ($this->bIncludeNameDetails) {
1420 if ($aResult['names']) {
1421 $aResult['sNameDetails'] = json_decode($aResult['names']);
1423 $aResult['sNameDetails'] = (object) array();
1427 // Adjust importance for the number of exact string matches in the result
1428 $aResult['importance'] = max(0.001, $aResult['importance']);
1430 $sAddress = $aResult['langaddress'];
1431 foreach ($aRecheckWords as $i => $sWord) {
1432 if (stripos($sAddress, $sWord)!==false) {
1434 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1438 $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
1440 $aResult['name'] = $aResult['langaddress'];
1441 // secondary ordering (for results with same importance (the smaller the better):
1442 // - approximate importance of address parts
1443 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1444 // - number of exact matches from the query
1445 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1446 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1447 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1448 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1450 // - importance of the class/type
1451 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1452 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1454 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1456 $aResult['foundorder'] += 0.01;
1458 if (CONST_Debug) var_dump($aResult);
1459 $aSearchResults[$iResNum] = $aResult;
1461 uasort($aSearchResults, 'byImportance');
1463 $aOSMIDDone = array();
1464 $aClassTypeNameDone = array();
1465 $aToFilter = $aSearchResults;
1466 $aSearchResults = array();
1469 foreach ($aToFilter as $iResNum => $aResult) {
1470 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1472 $fLat = $aResult['lat'];
1473 $fLon = $aResult['lon'];
1474 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1477 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1478 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1480 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1481 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1482 $aSearchResults[] = $aResult;
1485 // Absolute limit on number of results
1486 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1489 return $aSearchResults;