5 require_once(CONST_BasePath.'/lib/NearPoint.php');
6 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
13 protected $aLangPrefOrder = array();
15 protected $bIncludeAddressDetails = false;
16 protected $bIncludeExtraTags = false;
17 protected $bIncludeNameDetails = false;
19 protected $bIncludePolygonAsPoints = false;
20 protected $bIncludePolygonAsText = false;
21 protected $bIncludePolygonAsGeoJSON = false;
22 protected $bIncludePolygonAsKML = false;
23 protected $bIncludePolygonAsSVG = false;
24 protected $fPolygonSimplificationThreshold = 0.0;
26 protected $aExcludePlaceIDs = array();
27 protected $bDeDupe = true;
28 protected $bReverseInPlan = false;
30 protected $iLimit = 20;
31 protected $iFinalLimit = 10;
32 protected $iOffset = 0;
33 protected $bFallback = false;
35 protected $aCountryCodes = false;
37 protected $bBoundedSearch = false;
38 protected $aViewBox = false;
39 protected $sViewboxCentreSQL = false;
40 protected $sViewboxSmallSQL = false;
41 protected $sViewboxLargeSQL = false;
43 protected $iMaxRank = 20;
44 protected $iMinAddressRank = 0;
45 protected $iMaxAddressRank = 30;
46 protected $aAddressRankList = array();
47 protected $exactMatchCache = 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 setRoute($aRoutePoints, $fRouteWidth)
188 $this->aViewBox = false;
190 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
192 foreach ($aRoutePoints as $aPoint) {
193 $fPoint = (float)$aPoint;
194 $this->sViewboxCentreSQL .= $sSep.$fPoint;
195 $sSep = ($sSep == ' ') ? ',' : ' ';
197 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
199 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
200 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
202 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
203 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
206 public function setViewbox($aViewbox)
208 $this->aViewBox = array_map('floatval', $aViewbox);
210 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
211 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
212 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
213 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
215 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
216 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
218 userError("Bad parameter 'viewbox'. Not a box.");
221 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
222 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
223 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
224 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
225 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
226 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
228 $this->sViewboxCentreSQL = false;
229 $this->sViewboxSmallSQL = sprintf(
230 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
236 $this->sViewboxLargeSQL = sprintf(
237 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
245 public function setQuery($sQueryString)
247 $this->sQuery = $sQueryString;
248 $this->aStructuredQuery = false;
251 public function getQueryString()
253 return $this->sQuery;
257 public function loadParamArray($oParams)
259 $this->bIncludeAddressDetails
260 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
261 $this->bIncludeExtraTags
262 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
263 $this->bIncludeNameDetails
264 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
266 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
267 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
269 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
270 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
272 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
274 // List of excluded Place IDs - used for more acurate pageing
275 $sExcluded = $oParams->getStringList('exclude_place_ids');
277 foreach ($sExcluded as $iExcludedPlaceID) {
278 $iExcludedPlaceID = (int)$iExcludedPlaceID;
279 if ($iExcludedPlaceID)
280 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
283 if (isset($aExcludePlaceIDs))
284 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
287 // Only certain ranks of feature
288 $sFeatureType = $oParams->getString('featureType');
289 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
290 if ($sFeatureType) $this->setFeatureType($sFeatureType);
293 $sCountries = $oParams->getStringList('countrycodes');
295 foreach ($sCountries as $sCountryCode) {
296 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
297 $aCountries[] = strtolower($sCountryCode);
300 if (isset($aCountries))
301 $this->aCountryCodes = $aCountries;
304 $aViewbox = $oParams->getStringList('viewboxlbrt');
306 if (count($aViewbox) != 4) {
307 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
309 $this->setViewbox($aViewbox);
311 $aViewbox = $oParams->getStringList('viewbox');
313 if (count($aViewbox) != 4) {
314 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
316 $this->setViewBox($aViewbox);
318 $aRoute = $oParams->getStringList('route');
319 $fRouteWidth = $oParams->getFloat('routewidth');
320 if ($aRoute && $fRouteWidth) {
321 $this->setRoute($aRoute, $fRouteWidth);
327 public function setQueryFromParams($oParams)
330 $sQuery = $oParams->getString('q');
332 $this->setStructuredQuery(
333 $oParams->getString('amenity'),
334 $oParams->getString('street'),
335 $oParams->getString('city'),
336 $oParams->getString('county'),
337 $oParams->getString('state'),
338 $oParams->getString('country'),
339 $oParams->getString('postalcode')
341 $this->setReverseInPlan(false);
343 $this->setQuery($sQuery);
347 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
349 $sValue = trim($sValue);
350 if (!$sValue) return false;
351 $this->aStructuredQuery[$sKey] = $sValue;
352 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
353 $this->iMinAddressRank = $iNewMinAddressRank;
354 $this->iMaxAddressRank = $iNewMaxAddressRank;
356 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
360 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
362 $this->sQuery = false;
365 $this->iMinAddressRank = 0;
366 $this->iMaxAddressRank = 30;
367 $this->aAddressRankList = array();
369 $this->aStructuredQuery = array();
370 $this->sAllowedTypesSQLList = False;
372 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
373 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
374 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
375 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
376 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
377 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
378 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
380 if (sizeof($this->aStructuredQuery) > 0) {
381 $this->sQuery = join(', ', $this->aStructuredQuery);
382 if ($this->iMaxAddressRank < 30) {
383 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
388 public function fallbackStructuredQuery()
390 if (!$this->aStructuredQuery) return false;
392 $aParams = $this->aStructuredQuery;
394 if (sizeof($aParams) == 1) return false;
396 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
398 foreach ($aOrderToFallback as $sType) {
399 if (isset($aParams[$sType])) {
400 unset($aParams[$sType]);
401 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
409 public function getDetails($aPlaceIDs)
411 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
412 if (sizeof($aPlaceIDs) == 0) return array();
414 $sLanguagePrefArraySQL = getArraySQL(
415 array_map("getDBQuoted",
416 $this->aLangPrefOrder)
419 // Get the details for display (is this a redundant extra step?)
420 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
422 $sImportanceSQL = '';
423 $sImportanceSQLGeom = '';
424 if ($this->sViewboxSmallSQL) {
425 $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
426 $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, geometry) THEN 1 ELSE 0.75 END * ";
428 if ($this->sViewboxLargeSQL) {
429 $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
430 $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, geometry) THEN 1 ELSE 0.75 END * ";
434 $sSQL .= " osm_type,";
438 $sSQL .= " admin_level,";
439 $sSQL .= " rank_search,";
440 $sSQL .= " rank_address,";
441 $sSQL .= " min(place_id) AS place_id, ";
442 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
443 $sSQL .= " country_code, ";
444 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
445 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
446 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
447 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
448 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
449 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
450 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
451 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
453 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
455 $sSQL .= " place_addressline s, ";
456 $sSQL .= " placex p";
457 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
458 $sSQL .= " AND p.place_id = s.address_place_id ";
459 $sSQL .= " AND s.isaddress ";
460 $sSQL .= " AND p.importance is not null ";
461 $sSQL .= " ) AS addressimportance, ";
462 $sSQL .= " (extratags->'place') AS extra_place ";
463 $sSQL .= " FROM placex";
464 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
466 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
467 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
468 $sSQL .= " OR (extratags->'place') = 'city'";
470 if ($this->aAddressRankList) {
471 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
474 if ($this->sAllowedTypesSQLList) {
475 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
477 $sSQL .= " AND linked_place_id is null ";
478 $sSQL .= " GROUP BY ";
479 $sSQL .= " osm_type, ";
480 $sSQL .= " osm_id, ";
483 $sSQL .= " admin_level, ";
484 $sSQL .= " rank_search, ";
485 $sSQL .= " rank_address, ";
486 $sSQL .= " country_code, ";
487 $sSQL .= " importance, ";
488 if (!$this->bDeDupe) $sSQL .= "place_id,";
489 $sSQL .= " langaddress, ";
490 $sSQL .= " placename, ";
492 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
493 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
494 $sSQL .= " extratags->'place' ";
499 $sSQL .= " 'P' as osm_type,";
500 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
501 $sSQL .= " 'place' as class, 'postcode' as type,";
502 $sSQL .= " null as admin_level, rank_search, rank_address,";
503 $sSQL .= " place_id, parent_place_id, country_code,";
504 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
505 $sSQL .= " postcode as placename,";
506 $sSQL .= " postcode as ref,";
507 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
508 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
509 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
510 $sSQL .= $sImportanceSQLGeom."(0.75-(rank_search::float/40)) AS importance, ";
512 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
514 $sSQL .= " place_addressline s, ";
515 $sSQL .= " placex p";
516 $sSQL .= " WHERE s.place_id = lp.parent_place_id";
517 $sSQL .= " AND p.place_id = s.address_place_id ";
518 $sSQL .= " AND s.isaddress";
519 $sSQL .= " AND p.importance is not null";
520 $sSQL .= " ) AS addressimportance, ";
521 $sSQL .= " null AS extra_place ";
522 $sSQL .= "FROM location_postcode lp";
523 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
525 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
526 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
527 // with start- and endnumber, the common osm housenumbers are usually saved as points
530 $length = count($aPlaceIDs);
531 foreach ($aPlaceIDs as $placeID => $housenumber) {
533 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
534 if ($i<$length) $sHousenumbers .= ", ";
537 if (CONST_Use_US_Tiger_Data) {
538 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
541 $sSQL .= " 'T' AS osm_type, ";
542 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
543 $sSQL .= " 'place' AS class, ";
544 $sSQL .= " 'house' AS type, ";
545 $sSQL .= " null AS admin_level, ";
546 $sSQL .= " 30 AS rank_search, ";
547 $sSQL .= " 30 AS rank_address, ";
548 $sSQL .= " min(place_id) AS place_id, ";
549 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
550 $sSQL .= " 'us' AS country_code, ";
551 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
552 $sSQL .= " null AS placename, ";
553 $sSQL .= " null AS ref, ";
554 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
555 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
556 $sSQL .= " avg(st_x(centroid)) AS lon, ";
557 $sSQL .= " avg(st_y(centroid)) AS lat,";
558 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
560 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
562 $sSQL .= " place_addressline s, ";
563 $sSQL .= " placex p";
564 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
565 $sSQL .= " AND p.place_id = s.address_place_id ";
566 $sSQL .= " AND s.isaddress";
567 $sSQL .= " AND p.importance is not null";
568 $sSQL .= " ) AS addressimportance, ";
569 $sSQL .= " null AS extra_place ";
571 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
572 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
573 $sSQL .= " parent_place_id, ";
574 $sSQL .= " housenumber_for_place";
576 $sSQL .= " location_property_tiger ";
577 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
579 $sSQL .= " housenumber_for_place>=0";
580 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
581 $sSQL .= " ) AS blub"; //postgres wants an alias here
582 $sSQL .= " GROUP BY";
583 $sSQL .= " place_id, ";
584 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
585 if (!$this->bDeDupe) $sSQL .= ", place_id ";
588 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
591 $sSQL .= " 'W' AS osm_type, ";
592 $sSQL .= " osm_id, ";
593 $sSQL .= " 'place' AS class, ";
594 $sSQL .= " 'house' AS type, ";
595 $sSQL .= " null AS admin_level, ";
596 $sSQL .= " 30 AS rank_search, ";
597 $sSQL .= " 30 AS rank_address, ";
598 $sSQL .= " min(place_id) as place_id, ";
599 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
600 $sSQL .= " country_code, ";
601 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
602 $sSQL .= " null AS placename, ";
603 $sSQL .= " null AS ref, ";
604 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
605 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
606 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
607 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
608 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
611 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
613 $sSQL .= " place_addressline s, ";
614 $sSQL .= " placex p";
615 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
616 $sSQL .= " AND p.place_id = s.address_place_id ";
617 $sSQL .= " AND s.isaddress ";
618 $sSQL .= " AND p.importance is not null";
619 $sSQL .= " ) AS addressimportance,";
620 $sSQL .= " null AS extra_place ";
623 $sSQL .= " osm_id, ";
624 $sSQL .= " place_id, ";
625 $sSQL .= " country_code, ";
626 $sSQL .= " CASE "; // interpolate the housenumbers here
627 $sSQL .= " WHEN startnumber != endnumber ";
628 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
629 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
630 $sSQL .= " END as centroid, ";
631 $sSQL .= " parent_place_id, ";
632 $sSQL .= " housenumber_for_place ";
634 $sSQL .= " location_property_osmline ";
635 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
637 $sSQL .= " WHERE housenumber_for_place>=0 ";
638 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
639 $sSQL .= " ) as blub"; //postgres wants an alias here
640 $sSQL .= " GROUP BY ";
641 $sSQL .= " osm_id, ";
642 $sSQL .= " place_id, ";
643 $sSQL .= " housenumber_for_place, ";
644 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
645 if (!$this->bDeDupe) $sSQL .= ", place_id ";
647 if (CONST_Use_Aux_Location_data) {
650 $sSQL .= " 'L' AS osm_type, ";
651 $sSQL .= " place_id AS osm_id, ";
652 $sSQL .= " 'place' AS class,";
653 $sSQL .= " 'house' AS type, ";
654 $sSQL .= " null AS admin_level, ";
655 $sSQL .= " 0 AS rank_search,";
656 $sSQL .= " 0 AS rank_address, ";
657 $sSQL .= " min(place_id) AS place_id,";
658 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
659 $sSQL .= " 'us' AS country_code, ";
660 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
661 $sSQL .= " null AS placename, ";
662 $sSQL .= " null AS ref, ";
663 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
664 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
665 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
666 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
667 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
669 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
671 $sSQL .= " place_addressline s, ";
672 $sSQL .= " placex p";
673 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
674 $sSQL .= " AND p.place_id = s.address_place_id ";
675 $sSQL .= " AND s.isaddress";
676 $sSQL .= " AND p.importance is not null";
677 $sSQL .= " ) AS addressimportance, ";
678 $sSQL .= " null AS extra_place ";
679 $sSQL .= " FROM location_property_aux ";
680 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
681 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
682 $sSQL .= " GROUP BY ";
683 $sSQL .= " place_id, ";
684 if (!$this->bDeDupe) $sSQL .= "place_id, ";
685 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
689 $sSQL .= " order by importance desc";
694 $aSearchResults = chksql(
695 $this->oDB->getAll($sSQL),
696 "Could not get details for place."
699 return $aSearchResults;
702 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
705 Calculate all searches using aValidTokens i.e.
706 'Wodsworth Road, Sheffield' =>
710 0 1 (wodsworth)(road)
713 Score how good the search is so they can be ordered
717 foreach ($aPhrases as $iPhrase => $aPhrase) {
718 $aNewPhraseSearches = array();
719 if ($bStructuredPhrases) {
720 $sPhraseType = $aPhraseTypes[$iPhrase];
725 foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
726 // Too many permutations - too expensive
727 if ($iWordSet > 120) break;
729 $aWordsetSearches = $aSearches;
731 // Add all words from this wordset
732 foreach ($aWordset as $iToken => $sToken) {
733 //echo "<br><b>$sToken</b>";
734 $aNewWordsetSearches = array();
736 foreach ($aWordsetSearches as $oCurrentSearch) {
738 //var_dump($oCurrentSearch);
741 // If the token is valid
742 if (isset($aValidTokens[' '.$sToken])) {
743 // Recheck if the original word shows up in the query.
744 $bWordInQuery = false;
745 if (isset($aSearchTerm['word']) && $aSearchTerm['word']) {
746 $bWordInQuery = $this->normTerm($aSearchTerm['word'])) !== false;
748 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
749 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
752 isset($aValidTokens[$sToken])
753 && strpos($sToken, ' ') === false,
755 $iToken == 0 && $iPhrase == 0,
757 $iToken + 1 == sizeof($aWordset)
758 && $iPhrase + 1 == sizeof($aPhrases),
762 foreach ($aNewSearches as $oSearch) {
763 if ($oSearch->getRank() < $this->iMaxRank) {
764 $aNewWordsetSearches[] = $oSearch;
769 // Look for partial matches.
770 // Note that there is no point in adding country terms here
771 // because country is omitted in the address.
772 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
773 // Allow searching for a word - but at extra cost
774 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
775 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
779 $aWordFrequencyScores,
780 isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
783 foreach ($aNewSearches as $oSearch) {
784 if ($oSearch->getRank() < $this->iMaxRank) {
785 $aNewWordsetSearches[] = $oSearch;
793 usort($aNewWordsetSearches, 'bySearchRank');
794 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
796 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
798 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
799 usort($aNewPhraseSearches, 'bySearchRank');
801 $aSearchHash = array();
802 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
803 $sHash = serialize($aSearch);
804 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
805 else $aSearchHash[$sHash] = 1;
808 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
811 // Re-group the searches by their score, junk anything over 20 as just not worth trying
812 $aGroupedSearches = array();
813 foreach ($aNewPhraseSearches as $aSearch) {
814 $iRank = $aSearch->getRank();
815 if ($iRank < $this->iMaxRank) {
816 if (!isset($aGroupedSearches[$iRank])) {
817 $aGroupedSearches[$iRank] = array();
819 $aGroupedSearches[$iRank][] = $aSearch;
822 ksort($aGroupedSearches);
825 $aSearches = array();
826 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
827 $iSearchCount += sizeof($aNewSearches);
828 $aSearches = array_merge($aSearches, $aNewSearches);
829 if ($iSearchCount > 50) break;
832 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
835 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
836 $aGroupedSearches = array();
837 foreach ($aSearches as $oSearch) {
838 if (!$oSearch->isValidSearch()) {
842 $iRank = $oSearch->addToRank($iGlobalRank);
843 if (!isset($aGroupedSearches[$iRank]) {
844 $aGroupedSearches[$iRank] = array();
846 $aGroupedSearches[$iRank][] = $oSearch;
848 ksort($aGroupedSearches);
850 return $aGroupedSearches;
853 /* Perform the actual query lookup.
855 Returns an ordered list of results, each with the following fields:
856 osm_type: type of corresponding OSM object
860 P - postcode (internally computed)
861 osm_id: id of corresponding OSM object
862 class: general object class (corresponds to tag key of primary OSM tag)
863 type: subclass of object (corresponds to tag value of primary OSM tag)
864 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
865 rank_search: rank in search hierarchy
866 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
867 rank_address: rank in address hierarchy (determines orer in address)
868 place_id: internal key (may differ between different instances)
869 country_code: ISO country code
870 langaddress: localized full address
871 placename: localized name of object
872 ref: content of ref tag (if available)
875 importance: importance of place based on Wikipedia link count
876 addressimportance: cumulated importance of address elements
877 extra_place: type of place (for admin boundaries, if there is a place tag)
878 aBoundingBox: bounding Box
879 label: short description of the object class/type (English only)
880 name: full name (currently the same as langaddress)
881 foundorder: secondary ordering for places with same importance
885 public function lookup()
887 if (!$this->sQuery && !$this->aStructuredQuery) return array();
889 $sNormQuery = $this->normTerm($this->sQuery);
890 $sLanguagePrefArraySQL = getArraySQL(
891 array_map("getDBQuoted",
892 $this->aLangPrefOrder)
894 $sCountryCodesSQL = false;
895 if ($this->aCountryCodes) {
896 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
899 $sQuery = $this->sQuery;
900 if (!preg_match('//u', $sQuery)) {
901 userError("Query string is not UTF-8 encoded.");
904 // Conflicts between US state abreviations and various words for 'the' in different languages
905 if (isset($this->aLangPrefOrder['name:en'])) {
906 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
907 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
908 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
911 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
912 if ($this->sViewboxCentreSQL) {
913 // For complex viewboxes (routes) precompute the bounding geometry
915 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
916 "Could not get small viewbox"
918 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
921 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
922 "Could not get large viewbox"
924 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
927 // Do we have anything that looks like a lat/lon pair?
929 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
930 $oNearPoint = $aLooksLike['pt'];
931 $sQuery = $aLooksLike['query'];
934 $aSearchResults = array();
935 if ($sQuery || $this->aStructuredQuery) {
936 // Start with a single blank search
937 $aSearches = array(new SearchDescription());
940 $aSearches[0]->setNear($oNearPoint);
944 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
950 '/\\[([\\w ]*)\\]/u',
955 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
956 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
957 if (!$sSpecialTerm) {
958 $sSpecialTerm = $aSpecialTerm[1];
962 if (!$sSpecialTerm && $this->aStructuredQuery
963 && isset($this->aStructuredQuery['amenity'])) {
964 $sSpecialTerm = $this->aStructuredQuery['amenity'];
965 unset($this->aStructuredQuery['amenity']);
968 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
969 $sSpecialTerm = pg_escape_string($sSpecialTerm);
971 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
972 "Cannot decode query. Wrong encoding?"
974 $sSQL = 'SELECT class, type FROM word ';
975 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
976 $sSQL .= ' AND class is not null AND class not in (\'place\')';
977 if (CONST_Debug) var_Dump($sSQL);
978 $aSearchWords = chksql($this->oDB->getAll($sSQL));
979 $aNewSearches = array();
980 foreach ($aSearches as $oSearch) {
981 foreach ($aSearchWords as $aSearchTerm) {
982 $oNewSearch = clone $oSearch;
983 $oNewSearch->setPoiSearch(
985 $aSearchTerm['class'],
986 $aSearchTerm['type'],
988 $aNewSearches[] = $oNewSearch;
991 $aSearches = $aNewSearches;
994 // Split query into phrases
995 // Commas are used to reduce the search space by indicating where phrases split
996 if ($this->aStructuredQuery) {
997 $aPhrases = $this->aStructuredQuery;
998 $bStructuredPhrases = true;
1000 $aPhrases = explode(',', $sQuery);
1001 $bStructuredPhrases = false;
1004 // Convert each phrase to standard form
1005 // Create a list of standard words
1006 // Get all 'sets' of words
1007 // Generate a complete list of all
1009 foreach ($aPhrases as $iPhrase => $sPhrase) {
1011 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1012 "Cannot normalize query string (is it a UTF-8 string?)"
1014 if (trim($aPhrase['string'])) {
1015 $aPhrases[$iPhrase] = $aPhrase;
1016 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1017 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1018 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1020 unset($aPhrases[$iPhrase]);
1024 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1025 $aPhraseTypes = array_keys($aPhrases);
1026 $aPhrases = array_values($aPhrases);
1028 if (sizeof($aTokens)) {
1029 // Check which tokens we have, get the ID numbers
1030 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1031 $sSQL .= ' FROM word ';
1032 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1034 if (CONST_Debug) var_Dump($sSQL);
1036 $aValidTokens = array();
1037 $aDatabaseWords = chksql(
1038 $this->oDB->getAll($sSQL),
1039 "Could not get word tokens."
1041 $aPossibleMainWordIDs = array();
1042 $aWordFrequencyScores = array();
1043 foreach ($aDatabaseWords as $aToken) {
1044 // Very special case - require 2 letter country param to match the country code found
1045 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1046 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1051 if (isset($aValidTokens[$aToken['word_token']])) {
1052 $aValidTokens[$aToken['word_token']][] = $aToken;
1054 $aValidTokens[$aToken['word_token']] = array($aToken);
1056 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1057 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1059 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1061 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1062 foreach ($aTokens as $sToken) {
1063 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1064 if (isset($aValidTokens[$aData[1]])) {
1065 foreach ($aValidTokens[$aData[1]] as $aToken) {
1066 if (!$aToken['class']) {
1067 if (isset($aValidTokens[$sToken])) {
1068 $aValidTokens[$sToken][] = $aToken;
1070 $aValidTokens[$sToken] = array($aToken);
1078 foreach ($aTokens as $sToken) {
1079 // Unknown single word token with a number - assume it is a house number
1080 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1081 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1085 // Any words that have failed completely?
1086 // TODO: suggestions
1088 // Start the search process
1089 // array with: placeid => -1 | tiger-housenumber
1090 $aResultPlaceIDs = array();
1092 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1094 if ($this->bReverseInPlan) {
1095 // Reverse phrase array and also reverse the order of the wordsets in
1096 // the first and final phrase. Don't bother about phrases in the middle
1097 // because order in the address doesn't matter.
1098 $aPhrases = array_reverse($aPhrases);
1099 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1100 if (sizeof($aPhrases) > 1) {
1101 $aFinalPhrase = end($aPhrases);
1102 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1104 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1106 foreach ($aGroupedSearches as $aSearches) {
1107 foreach ($aSearches as $aSearch) {
1108 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1109 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1111 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1115 $aGroupedSearches = $aReverseGroupedSearches;
1116 ksort($aGroupedSearches);
1119 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1120 $aGroupedSearches = array();
1121 foreach ($aSearches as $aSearch) {
1122 if ($aSearch->getRank() < $this->iMaxRank) {
1123 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1124 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1127 ksort($aGroupedSearches);
1130 // Filter out duplicate searches
1131 $aSearchHash = array();
1132 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1133 foreach ($aSearches as $iSearch => $aSearch) {
1134 $sHash = serialize($aSearch);
1135 if (isset($aSearchHash[$sHash])) {
1136 unset($aGroupedSearches[$iGroup][$iSearch]);
1137 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1139 $aSearchHash[$sHash] = 1;
1144 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1148 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1150 foreach ($aSearches as $oSearch) {
1152 $searchedHousenumber = -1;
1154 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1155 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1157 $aPlaceIDs = array();
1158 if ($oSearch->isCountrySearch()) {
1159 // Just looking for a country - look it up
1160 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1161 $aPlaceIDs = $oSearch->queryCountry(
1163 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : ''
1166 } elseif (!$oSearch->isNamedSearch()) {
1167 // looking for a POI in a geographic area
1168 if (!$bBoundingBoxSearch && !$oSearch->isNearSearch()) {
1172 $aPlaceIDs = $oSearch->queryNearbyPoi(
1175 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
1177 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1180 } elseif ($oSearch->isOperator(Operator::POSTCODE)) {
1181 $aPlaceIDs = $oSearch->queryPostcode(
1188 // First search for places according to name and address.
1189 $aNamedPlaceIDs = $oSearch->queryNamedPlace(
1191 $aWordFrequencyScores,
1193 $this->iMinAddressRank,
1194 $this->iMaxAddressRank,
1195 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1196 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
1197 $bBoundingBoxSearch ? $this->sViewboxLargeSQL : '',
1201 if (sizeof($aNamedPlaceIDs)) {
1202 foreach ($aNamedPlaceIDs as $aRow) {
1203 $aPlaceIDs[] = $aRow['place_id'];
1204 $this->exactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
1208 //now search for housenumber, if housenumber provided
1209 if ($oSearch->hasHouseNumber() && sizeof($aPlaceIDs)) {
1210 $aResult = $oSearch->queryHouseNumber(
1213 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : ''
1217 if (sizeof($aResult)) {
1218 $searchedHousenumber = $aResult['iHouseNumber'];
1219 $aPlaceIDs = $aResults['aPlaceIDs'];
1220 } elseif (!$oSearch->looksLikeFullAddress()) {
1221 $aPlaceIDs = array();
1225 // finally get POIs if requested
1226 if ($oSearch->isPoiSearch() && sizeof($aPlaceIDs)) {
1227 $aPlaceIDs = $oSearch->queryPoiByOperator(
1230 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : ''
1237 echo "<br><b>Place IDs:</b> ";
1238 var_Dump($aPlaceIDs);
1241 if (sizeof($aPlaceIDs) && $oSearch->getPostcode()) {
1242 $sSQL = 'SELECT place_id FROM placex';
1243 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
1244 $sSQL .= " AND postcode = '".$oSearch->getPostcode()."'";
1245 if (CONST_Debug) var_dump($sSQL);
1246 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1247 if ($aFilteredPlaceIDs) {
1248 $aPlaceIDs = $aFilteredPlaceIDs;
1250 echo "<br><b>Place IDs after postcode filtering:</b> ";
1251 var_Dump($aPlaceIDs);
1256 foreach ($aPlaceIDs as $iPlaceID) {
1257 // array for placeID => -1 | Tiger housenumber
1258 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1260 if ($iQueryLoop > 20) break;
1263 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1264 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1265 // reduces the number of place ids, like a filter
1266 // rank_address is 30 for interpolated housenumbers
1267 $sWherePlaceId = 'WHERE place_id in (';
1268 $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1270 $sSQL = "SELECT place_id ";
1271 $sSQL .= "FROM placex ".$sWherePlaceId;
1273 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1274 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1275 $sSQL .= " OR (extratags->'place') = 'city'";
1277 if ($this->aAddressRankList) {
1278 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1280 $sSQL .= " ) UNION ";
1281 $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1282 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1283 if ($this->aAddressRankList) {
1284 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1287 if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1289 $sSQL .= " SELECT place_id ";
1290 $sSQL .= " FROM location_property_tiger ".$sWherePlaceId;
1292 if ($this->iMaxAddressRank == 30) {
1294 $sSQL .= " SELECT place_id ";
1295 $sSQL .= " FROM location_property_osmline ".$sWherePlaceId;
1297 if (CONST_Debug) var_dump($sSQL);
1298 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1300 foreach ($aFilteredPlaceIDs as $placeID) {
1301 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1303 $aResultPlaceIDs = $tempIDs;
1307 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1308 if ($iGroupLoop > 4) break;
1309 if ($iQueryLoop > 30) break;
1312 // Did we find anything?
1313 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1314 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1317 // Just interpret as a reverse geocode
1318 $oReverse = new ReverseGeocode($this->oDB);
1319 $oReverse->setZoom(18);
1321 $aLookup = $oReverse->lookup(
1327 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1329 if ($aLookup['place_id']) {
1330 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1331 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1333 $aSearchResults = array();
1338 if (!sizeof($aSearchResults)) {
1339 if ($this->bFallback) {
1340 if ($this->fallbackStructuredQuery()) {
1341 return $this->lookup();
1348 $aClassType = getClassTypesWithImportance();
1349 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1350 foreach ($aRecheckWords as $i => $sWord) {
1351 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1355 echo '<i>Recheck words:<\i>';
1356 var_dump($aRecheckWords);
1359 $oPlaceLookup = new PlaceLookup($this->oDB);
1360 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1361 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1362 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1363 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1364 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1365 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1367 foreach ($aSearchResults as $iResNum => $aResult) {
1369 $fDiameter = getResultDiameter($aResult);
1371 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1372 if ($aOutlineResult) {
1373 $aResult = array_merge($aResult, $aOutlineResult);
1376 if ($aResult['extra_place'] == 'city') {
1377 $aResult['class'] = 'place';
1378 $aResult['type'] = 'city';
1379 $aResult['rank_search'] = 16;
1382 // Is there an icon set for this type of result?
1383 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1384 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1386 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1389 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1390 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1392 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1393 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1394 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1396 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1398 // if tag '&addressdetails=1' is set in query
1399 if ($this->bIncludeAddressDetails) {
1400 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1401 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1402 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1403 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1407 if ($this->bIncludeExtraTags) {
1408 if ($aResult['extra']) {
1409 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1411 $aResult['sExtraTags'] = (object) array();
1415 if ($this->bIncludeNameDetails) {
1416 if ($aResult['names']) {
1417 $aResult['sNameDetails'] = json_decode($aResult['names']);
1419 $aResult['sNameDetails'] = (object) array();
1423 // Adjust importance for the number of exact string matches in the result
1424 $aResult['importance'] = max(0.001, $aResult['importance']);
1426 $sAddress = $aResult['langaddress'];
1427 foreach ($aRecheckWords as $i => $sWord) {
1428 if (stripos($sAddress, $sWord)!==false) {
1430 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1434 $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
1436 $aResult['name'] = $aResult['langaddress'];
1437 // secondary ordering (for results with same importance (the smaller the better):
1438 // - approximate importance of address parts
1439 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1440 // - number of exact matches from the query
1441 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1442 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1443 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1444 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1446 // - importance of the class/type
1447 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1448 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1450 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1452 $aResult['foundorder'] += 0.01;
1454 if (CONST_Debug) var_dump($aResult);
1455 $aSearchResults[$iResNum] = $aResult;
1457 uasort($aSearchResults, 'byImportance');
1459 $aOSMIDDone = array();
1460 $aClassTypeNameDone = array();
1461 $aToFilter = $aSearchResults;
1462 $aSearchResults = array();
1465 foreach ($aToFilter as $iResNum => $aResult) {
1466 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1468 $fLat = $aResult['lat'];
1469 $fLon = $aResult['lon'];
1470 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1473 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1474 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1476 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1477 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1478 $aSearchResults[] = $aResult;
1481 // Absolute limit on number of results
1482 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1485 return $aSearchResults;