5 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
6 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
12 protected $aLangPrefOrder = array();
14 protected $bIncludeAddressDetails = false;
15 protected $bIncludeExtraTags = false;
16 protected $bIncludeNameDetails = false;
18 protected $bIncludePolygonAsPoints = false;
19 protected $bIncludePolygonAsText = false;
20 protected $bIncludePolygonAsGeoJSON = false;
21 protected $bIncludePolygonAsKML = false;
22 protected $bIncludePolygonAsSVG = false;
23 protected $fPolygonSimplificationThreshold = 0.0;
25 protected $aExcludePlaceIDs = array();
26 protected $bDeDupe = true;
27 protected $bReverseInPlan = false;
29 protected $iLimit = 20;
30 protected $iFinalLimit = 10;
31 protected $iOffset = 0;
32 protected $bFallback = false;
34 protected $aCountryCodes = false;
35 protected $aNearPoint = 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;
55 public function __construct(&$oDB)
60 public function setReverseInPlan($bReverse)
62 $this->bReverseInPlan = $bReverse;
65 public function setLanguagePreference($aLangPref)
67 $this->aLangPrefOrder = $aLangPref;
70 public function getIncludeAddressDetails()
72 return $this->bIncludeAddressDetails;
75 public function getIncludeExtraTags()
77 return $this->bIncludeExtraTags;
80 public function getIncludeNameDetails()
82 return $this->bIncludeNameDetails;
85 public function setIncludePolygonAsPoints($b = true)
87 $this->bIncludePolygonAsPoints = $b;
90 public function setIncludePolygonAsText($b = true)
92 $this->bIncludePolygonAsText = $b;
95 public function setIncludePolygonAsGeoJSON($b = true)
97 $this->bIncludePolygonAsGeoJSON = $b;
100 public function setIncludePolygonAsKML($b = true)
102 $this->bIncludePolygonAsKML = $b;
105 public function setIncludePolygonAsSVG($b = true)
107 $this->bIncludePolygonAsSVG = $b;
110 public function setPolygonSimplificationThreshold($f)
112 $this->fPolygonSimplificationThreshold = $f;
115 public function setLimit($iLimit = 10)
117 if ($iLimit > 50) $iLimit = 50;
118 if ($iLimit < 1) $iLimit = 1;
120 $this->iFinalLimit = $iLimit;
121 $this->iLimit = $iLimit + min($iLimit, 10);
124 public function getExcludedPlaceIDs()
126 return $this->aExcludePlaceIDs;
129 public function getViewBoxString()
131 if (!$this->aViewBox) return null;
132 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
135 public function setFeatureType($sFeatureType)
137 switch ($sFeatureType) {
139 $this->setRankRange(4, 4);
142 $this->setRankRange(8, 8);
145 $this->setRankRange(14, 16);
148 $this->setRankRange(8, 20);
153 public function setRankRange($iMin, $iMax)
155 $this->iMinAddressRank = $iMin;
156 $this->iMaxAddressRank = $iMax;
159 public function setRoute($aRoutePoints, $fRouteWidth)
161 $this->aViewBox = false;
163 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
165 foreach ($aRoutePoints as $aPoint) {
166 $fPoint = (float)$aPoint;
167 $this->sViewboxCentreSQL .= $sSep.$fPoint;
168 $sSep = ($sSep == ' ') ? ',' : ' ';
170 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
172 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
173 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
175 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
176 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
179 public function setViewbox($aViewbox)
181 $this->aViewBox = array_map('floatval', $aViewbox);
183 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
184 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
185 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
186 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
188 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
189 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
191 userError("Bad parameter 'viewbox'. Not a box.");
194 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
195 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
196 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
197 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
198 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
199 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
201 $this->sViewboxCentreSQL = false;
202 $this->sViewboxSmallSQL = sprintf(
203 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
209 $this->sViewboxLargeSQL = sprintf(
210 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
218 public function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
220 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
223 public function setQuery($sQueryString)
225 $this->sQuery = $sQueryString;
226 $this->aStructuredQuery = false;
229 public function getQueryString()
231 return $this->sQuery;
235 public function loadParamArray($oParams)
237 $this->bIncludeAddressDetails
238 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
239 $this->bIncludeExtraTags
240 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
241 $this->bIncludeNameDetails
242 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
244 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
245 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
247 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
248 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
250 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
252 // List of excluded Place IDs - used for more acurate pageing
253 $sExcluded = $oParams->getStringList('exclude_place_ids');
255 foreach ($sExcluded as $iExcludedPlaceID) {
256 $iExcludedPlaceID = (int)$iExcludedPlaceID;
257 if ($iExcludedPlaceID)
258 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
261 if (isset($aExcludePlaceIDs))
262 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
265 // Only certain ranks of feature
266 $sFeatureType = $oParams->getString('featureType');
267 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
268 if ($sFeatureType) $this->setFeatureType($sFeatureType);
271 $sCountries = $oParams->getStringList('countrycodes');
273 foreach ($sCountries as $sCountryCode) {
274 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
275 $aCountries[] = strtolower($sCountryCode);
278 if (isset($aCountries))
279 $this->aCountryCodes = $aCountries;
282 $aViewbox = $oParams->getStringList('viewboxlbrt');
284 if (count($aViewbox) != 4) {
285 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
287 $this->setViewbox($aViewbox);
289 $aViewbox = $oParams->getStringList('viewbox');
291 if (count($aViewbox) != 4) {
292 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
294 $this->setViewBox(array(
301 $aRoute = $oParams->getStringList('route');
302 $fRouteWidth = $oParams->getFloat('routewidth');
303 if ($aRoute && $fRouteWidth) {
304 $this->setRoute($aRoute, $fRouteWidth);
310 public function setQueryFromParams($oParams)
313 $sQuery = $oParams->getString('q');
315 $this->setStructuredQuery(
316 $oParams->getString('amenity'),
317 $oParams->getString('street'),
318 $oParams->getString('city'),
319 $oParams->getString('county'),
320 $oParams->getString('state'),
321 $oParams->getString('country'),
322 $oParams->getString('postalcode')
324 $this->setReverseInPlan(false);
326 $this->setQuery($sQuery);
330 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
332 $sValue = trim($sValue);
333 if (!$sValue) return false;
334 $this->aStructuredQuery[$sKey] = $sValue;
335 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
336 $this->iMinAddressRank = $iNewMinAddressRank;
337 $this->iMaxAddressRank = $iNewMaxAddressRank;
339 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
343 public function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
345 $this->sQuery = false;
348 $this->iMinAddressRank = 0;
349 $this->iMaxAddressRank = 30;
350 $this->aAddressRankList = array();
352 $this->aStructuredQuery = array();
353 $this->sAllowedTypesSQLList = '';
355 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
356 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
357 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
358 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
359 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
360 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
361 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
363 if (sizeof($this->aStructuredQuery) > 0) {
364 $this->sQuery = join(', ', $this->aStructuredQuery);
365 if ($this->iMaxAddressRank < 30) {
366 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
371 public function fallbackStructuredQuery()
373 if (!$this->aStructuredQuery) return false;
375 $aParams = $this->aStructuredQuery;
377 if (sizeof($aParams) == 1) return false;
379 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
381 foreach ($aOrderToFallback as $sType) {
382 if (isset($aParams[$sType])) {
383 unset($aParams[$sType]);
384 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
392 public function getDetails($aPlaceIDs)
394 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
395 if (sizeof($aPlaceIDs) == 0) return array();
397 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
399 // Get the details for display (is this a redundant extra step?)
400 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
402 $sImportanceSQL = '';
403 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
404 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
407 $sSQL .= " osm_type,";
411 $sSQL .= " admin_level,";
412 $sSQL .= " rank_search,";
413 $sSQL .= " rank_address,";
414 $sSQL .= " min(place_id) AS place_id, ";
415 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
416 $sSQL .= " calculated_country_code AS country_code, ";
417 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
418 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
419 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
420 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
421 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
422 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
423 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
424 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
426 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
428 $sSQL .= " place_addressline s, ";
429 $sSQL .= " placex p";
430 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
431 $sSQL .= " AND p.place_id = s.address_place_id ";
432 $sSQL .= " AND s.isaddress ";
433 $sSQL .= " AND p.importance is not null ";
434 $sSQL .= " ) AS addressimportance, ";
435 $sSQL .= " (extratags->'place') AS extra_place ";
436 $sSQL .= " FROM placex";
437 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
439 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
440 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
441 $sSQL .= " OR (extratags->'place') = 'city'";
443 if ($this->aAddressRankList) {
444 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
447 if ($this->sAllowedTypesSQLList) {
448 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
450 $sSQL .= " AND linked_place_id is null ";
451 $sSQL .= " GROUP BY ";
452 $sSQL .= " osm_type, ";
453 $sSQL .= " osm_id, ";
456 $sSQL .= " admin_level, ";
457 $sSQL .= " rank_search, ";
458 $sSQL .= " rank_address, ";
459 $sSQL .= " calculated_country_code, ";
460 $sSQL .= " importance, ";
461 if (!$this->bDeDupe) $sSQL .= "place_id,";
462 $sSQL .= " langaddress, ";
463 $sSQL .= " placename, ";
465 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
466 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
467 $sSQL .= " extratags->'place' ";
469 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
470 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
471 // with start- and endnumber, the common osm housenumbers are usually saved as points
474 $length = count($aPlaceIDs);
475 foreach ($aPlaceIDs as $placeID => $housenumber) {
477 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
478 if ($i<$length) $sHousenumbers .= ", ";
481 if (CONST_Use_US_Tiger_Data) {
482 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
485 $sSQL .= " 'T' AS osm_type, ";
486 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
487 $sSQL .= " 'place' AS class, ";
488 $sSQL .= " 'house' AS type, ";
489 $sSQL .= " null AS admin_level, ";
490 $sSQL .= " 30 AS rank_search, ";
491 $sSQL .= " 30 AS rank_address, ";
492 $sSQL .= " min(place_id) AS place_id, ";
493 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
494 $sSQL .= " 'us' AS country_code, ";
495 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
496 $sSQL .= " null AS placename, ";
497 $sSQL .= " null AS ref, ";
498 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
499 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
500 $sSQL .= " avg(st_x(centroid)) AS lon, ";
501 $sSQL .= " avg(st_y(centroid)) AS lat,";
502 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
504 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
506 $sSQL .= " place_addressline s, ";
507 $sSQL .= " placex p";
508 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
509 $sSQL .= " AND p.place_id = s.address_place_id ";
510 $sSQL .= " AND s.isaddress";
511 $sSQL .= " AND p.importance is not null";
512 $sSQL .= " ) AS addressimportance, ";
513 $sSQL .= " null AS extra_place ";
515 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
516 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
517 $sSQL .= " parent_place_id, ";
518 $sSQL .= " housenumber_for_place";
520 $sSQL .= " location_property_tiger ";
521 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
523 $sSQL .= " housenumber_for_place>=0";
524 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
525 $sSQL .= " ) AS blub"; //postgres wants an alias here
526 $sSQL .= " GROUP BY";
527 $sSQL .= " place_id, ";
528 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
529 if (!$this->bDeDupe) $sSQL .= ", place_id ";
532 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
535 $sSQL .= " 'W' AS osm_type, ";
536 $sSQL .= " osm_id, ";
537 $sSQL .= " 'place' AS class, ";
538 $sSQL .= " 'house' AS type, ";
539 $sSQL .= " null AS admin_level, ";
540 $sSQL .= " 30 AS rank_search, ";
541 $sSQL .= " 30 AS rank_address, ";
542 $sSQL .= " min(place_id) as place_id, ";
543 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
544 $sSQL .= " calculated_country_code AS country_code, ";
545 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
546 $sSQL .= " null AS placename, ";
547 $sSQL .= " null AS ref, ";
548 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
549 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
550 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
551 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
552 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
555 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
557 $sSQL .= " place_addressline s, ";
558 $sSQL .= " placex p";
559 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
560 $sSQL .= " AND p.place_id = s.address_place_id ";
561 $sSQL .= " AND s.isaddress ";
562 $sSQL .= " AND p.importance is not null";
563 $sSQL .= " ) AS addressimportance,";
564 $sSQL .= " null AS extra_place ";
567 $sSQL .= " osm_id, ";
568 $sSQL .= " place_id, ";
569 $sSQL .= " calculated_country_code, ";
570 $sSQL .= " CASE "; // interpolate the housenumbers here
571 $sSQL .= " WHEN startnumber != endnumber ";
572 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
573 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
574 $sSQL .= " END as centroid, ";
575 $sSQL .= " parent_place_id, ";
576 $sSQL .= " housenumber_for_place ";
578 $sSQL .= " location_property_osmline ";
579 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
581 $sSQL .= " WHERE housenumber_for_place>=0 ";
582 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
583 $sSQL .= " ) as blub"; //postgres wants an alias here
584 $sSQL .= " GROUP BY ";
585 $sSQL .= " osm_id, ";
586 $sSQL .= " place_id, ";
587 $sSQL .= " housenumber_for_place, ";
588 $sSQL .= " calculated_country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
589 if (!$this->bDeDupe) $sSQL .= ", place_id ";
591 if (CONST_Use_Aux_Location_data) {
594 $sSQL .= " 'L' AS osm_type, ";
595 $sSQL .= " place_id AS osm_id, ";
596 $sSQL .= " 'place' AS class,";
597 $sSQL .= " 'house' AS type, ";
598 $sSQL .= " null AS admin_level, ";
599 $sSQL .= " 0 AS rank_search,";
600 $sSQL .= " 0 AS rank_address, ";
601 $sSQL .= " min(place_id) AS place_id,";
602 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
603 $sSQL .= " 'us' AS country_code, ";
604 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
605 $sSQL .= " null AS placename, ";
606 $sSQL .= " null AS ref, ";
607 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
608 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
609 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
610 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
611 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
613 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
615 $sSQL .= " place_addressline s, ";
616 $sSQL .= " placex p";
617 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
618 $sSQL .= " AND p.place_id = s.address_place_id ";
619 $sSQL .= " AND s.isaddress";
620 $sSQL .= " AND p.importance is not null";
621 $sSQL .= " ) AS addressimportance, ";
622 $sSQL .= " null AS extra_place ";
623 $sSQL .= " FROM location_property_aux ";
624 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
625 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
626 $sSQL .= " GROUP BY ";
627 $sSQL .= " place_id, ";
628 if (!$this->bDeDupe) $sSQL .= "place_id, ";
629 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
633 $sSQL .= " order by importance desc";
638 $aSearchResults = chksql(
639 $this->oDB->getAll($sSQL),
640 "Could not get details for place."
643 return $aSearchResults;
646 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
649 Calculate all searches using aValidTokens i.e.
650 'Wodsworth Road, Sheffield' =>
654 0 1 (wodsworth)(road)
657 Score how good the search is so they can be ordered
659 foreach ($aPhrases as $iPhrase => $sPhrase) {
660 $aNewPhraseSearches = array();
661 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
662 else $sPhraseType = '';
664 foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
665 // Too many permutations - too expensive
666 if ($iWordSet > 120) break;
668 $aWordsetSearches = $aSearches;
670 // Add all words from this wordset
671 foreach ($aWordset as $iToken => $sToken) {
672 //echo "<br><b>$sToken</b>";
673 $aNewWordsetSearches = array();
675 foreach ($aWordsetSearches as $aCurrentSearch) {
677 //var_dump($aCurrentSearch);
680 // If the token is valid
681 if (isset($aValidTokens[' '.$sToken])) {
682 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
683 $aSearch = $aCurrentSearch;
684 $aSearch['iSearchRank']++;
685 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
686 if ($aSearch['sCountryCode'] === false) {
687 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
688 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
689 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
690 $aSearch['iSearchRank'] += 5;
692 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
694 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
695 if ($aSearch['fLat'] === '') {
696 $aSearch['fLat'] = $aSearchTerm['lat'];
697 $aSearch['fLon'] = $aSearchTerm['lon'];
698 $aSearch['fRadius'] = $aSearchTerm['radius'];
699 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
701 } elseif ($sPhraseType == 'postalcode') {
702 // We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
703 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
704 // If we already have a name try putting the postcode first
705 if (sizeof($aSearch['aName'])) {
706 $aNewSearch = $aSearch;
707 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
708 $aNewSearch['aName'] = array();
709 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
710 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
713 if (sizeof($aSearch['aName'])) {
714 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
715 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
717 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
718 $aSearch['iSearchRank'] += 1000; // skip;
721 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
722 //$aSearch['iNamePhrase'] = $iPhrase;
724 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
726 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
727 if ($aSearch['sHouseNumber'] === '') {
728 $aSearch['sHouseNumber'] = $sToken;
729 // sanity check: if the housenumber is not mainly made
730 // up of numbers, add a penalty
731 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
732 // also housenumbers should appear in the first or second phrase
733 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
734 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
736 // Fall back to not searching for this item (better than nothing)
737 $aSearch = $aCurrentSearch;
738 $aSearch['iSearchRank'] += 1;
739 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
742 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
743 if ($aSearch['sClass'] === '') {
744 $aSearch['sOperator'] = $aSearchTerm['operator'];
745 $aSearch['sClass'] = $aSearchTerm['class'];
746 $aSearch['sType'] = $aSearchTerm['type'];
747 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
748 else $aSearch['sOperator'] = 'near'; // near = in for the moment
749 if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
751 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
753 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
754 if (sizeof($aSearch['aName'])) {
755 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
756 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
758 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
759 $aSearch['iSearchRank'] += 1000; // skip;
762 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
763 //$aSearch['iNamePhrase'] = $iPhrase;
765 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
769 // Look for partial matches.
770 // Note that there is no point in adding country terms here
771 // because country are 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 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
776 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
777 $aSearch = $aCurrentSearch;
778 $aSearch['iSearchRank'] += 1;
779 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
780 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
781 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
782 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
783 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
784 $aSearch['iSearchRank'] += 1;
785 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
786 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
787 if (empty($aSearchTermToken['country_code'])
788 && empty($aSearchTermToken['lat'])
789 && empty($aSearchTermToken['class'])
791 $aSearch = $aCurrentSearch;
792 $aSearch['iSearchRank'] += 1;
793 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
794 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
798 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
799 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
800 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
804 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
805 $aSearch = $aCurrentSearch;
806 $aSearch['iSearchRank'] += 1;
807 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
808 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
809 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
810 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
812 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
814 $aSearch['iNamePhrase'] = $iPhrase;
815 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
820 // Allow skipping a word - but at EXTREAM cost
821 //$aSearch = $aCurrentSearch;
822 //$aSearch['iSearchRank']+=100;
823 //$aNewWordsetSearches[] = $aSearch;
827 usort($aNewWordsetSearches, 'bySearchRank');
828 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
830 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
832 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
833 usort($aNewPhraseSearches, 'bySearchRank');
835 $aSearchHash = array();
836 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
837 $sHash = serialize($aSearch);
838 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
839 else $aSearchHash[$sHash] = 1;
842 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
845 // Re-group the searches by their score, junk anything over 20 as just not worth trying
846 $aGroupedSearches = array();
847 foreach ($aNewPhraseSearches as $aSearch) {
848 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
849 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
850 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
853 ksort($aGroupedSearches);
856 $aSearches = array();
857 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
858 $iSearchCount += sizeof($aNewSearches);
859 $aSearches = array_merge($aSearches, $aNewSearches);
860 if ($iSearchCount > 50) break;
863 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
865 return $aGroupedSearches;
868 /* Perform the actual query lookup.
870 Returns an ordered list of results, each with the following fields:
871 osm_type: type of corresponding OSM object
875 P - postcode (internally computed)
876 osm_id: id of corresponding OSM object
877 class: general object class (corresponds to tag key of primary OSM tag)
878 type: subclass of object (corresponds to tag value of primary OSM tag)
879 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
880 rank_search: rank in search hierarchy
881 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
882 rank_address: rank in address hierarchy (determines orer in address)
883 place_id: internal key (may differ between different instances)
884 country_code: ISO country code
885 langaddress: localized full address
886 placename: localized name of object
887 ref: content of ref tag (if available)
890 importance: importance of place based on Wikipedia link count
891 addressimportance: cumulated importance of address elements
892 extra_place: type of place (for admin boundaries, if there is a place tag)
893 aBoundingBox: bounding Box
894 label: short description of the object class/type (English only)
895 name: full name (currently the same as langaddress)
896 foundorder: secondary ordering for places with same importance
900 public function lookup()
902 if (!$this->sQuery && !$this->aStructuredQuery) return false;
904 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
905 $sCountryCodesSQL = false;
906 if ($this->aCountryCodes) {
907 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
910 $sQuery = $this->sQuery;
912 // Conflicts between US state abreviations and various words for 'the' in different languages
913 if (isset($this->aLangPrefOrder['name:en'])) {
914 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
915 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
916 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
919 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
920 if ($this->sViewboxCentreSQL) {
921 // For complex viewboxes (routes) precompute the bounding geometry
923 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
924 "Could not get small viewbox"
926 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
929 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
930 "Could not get large viewbox"
932 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
935 // Do we have anything that looks like a lat/lon pair?
936 if ($aLooksLike = looksLikeLatLonPair($sQuery)) {
937 $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
938 $sQuery = $aLooksLike['query'];
941 $aSearchResults = array();
942 if ($sQuery || $this->aStructuredQuery) {
943 // Start with a blank search
948 'sCountryCode' => false,
950 'aAddress' => array(),
951 'aFullNameAddress' => array(),
952 'aNameNonSearch' => array(),
953 'aAddressNonSearch' => array(),
955 'aFeatureName' => array(),
958 'sHouseNumber' => '',
965 // Do we have a radius search?
966 $sNearPointSQL = false;
967 if ($this->aNearPoint) {
968 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
969 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
970 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
971 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
974 // Any 'special' terms in the search?
975 $bSpecialTerms = false;
976 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
977 $aSpecialTerms = array();
978 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
979 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
980 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
983 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
984 $aSpecialTerms = array();
985 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
986 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
987 unset($this->aStructuredQuery['amenity']);
990 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
991 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
992 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
995 $sSQL .= ' SELECT word_id, word_token, word, class, type, country_code, operator';
996 $sSQL .= ' FROM word ';
997 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
999 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1000 $sSQL .= ' OR country_code is not null';
1001 if (CONST_Debug) var_Dump($sSQL);
1002 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1003 $aNewSearches = array();
1004 foreach ($aSearches as $aSearch) {
1005 foreach ($aSearchWords as $aSearchTerm) {
1006 $aNewSearch = $aSearch;
1007 if ($aSearchTerm['country_code']) {
1008 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1009 $aNewSearches[] = $aNewSearch;
1010 $bSpecialTerms = true;
1012 if ($aSearchTerm['class']) {
1013 $aNewSearch['sClass'] = $aSearchTerm['class'];
1014 $aNewSearch['sType'] = $aSearchTerm['type'];
1015 $aNewSearches[] = $aNewSearch;
1016 $bSpecialTerms = true;
1020 $aSearches = $aNewSearches;
1023 // Split query into phrases
1024 // Commas are used to reduce the search space by indicating where phrases split
1025 if ($this->aStructuredQuery) {
1026 $aPhrases = $this->aStructuredQuery;
1027 $bStructuredPhrases = true;
1029 $aPhrases = explode(',', $sQuery);
1030 $bStructuredPhrases = false;
1033 // Convert each phrase to standard form
1034 // Create a list of standard words
1035 // Get all 'sets' of words
1036 // Generate a complete list of all
1038 foreach ($aPhrases as $iPhrase => $sPhrase) {
1040 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1041 "Cannot normalize query string (is it a UTF-8 string?)"
1043 if (trim($aPhrase['string'])) {
1044 $aPhrases[$iPhrase] = $aPhrase;
1045 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1046 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1047 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1049 unset($aPhrases[$iPhrase]);
1053 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1054 $aPhraseTypes = array_keys($aPhrases);
1055 $aPhrases = array_values($aPhrases);
1057 if (sizeof($aTokens)) {
1058 // Check which tokens we have, get the ID numbers
1059 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1060 $sSQL .= ' FROM word ';
1061 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1063 if (CONST_Debug) var_Dump($sSQL);
1065 $aValidTokens = array();
1066 if (sizeof($aTokens)) {
1067 $aDatabaseWords = chksql(
1068 $this->oDB->getAll($sSQL),
1069 "Could not get word tokens."
1072 $aDatabaseWords = array();
1074 $aPossibleMainWordIDs = array();
1075 $aWordFrequencyScores = array();
1076 foreach ($aDatabaseWords as $aToken) {
1077 // Very special case - require 2 letter country param to match the country code found
1078 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1079 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1084 if (isset($aValidTokens[$aToken['word_token']])) {
1085 $aValidTokens[$aToken['word_token']][] = $aToken;
1087 $aValidTokens[$aToken['word_token']] = array($aToken);
1089 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1090 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1092 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1094 // Try and calculate GB postcodes we might be missing
1095 foreach ($aTokens as $sToken) {
1096 // Source of gb postcodes is now definitive - always use
1097 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1098 if (substr($aData[1], -2, 1) != ' ') {
1099 $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1100 $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1102 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1103 if ($aGBPostcodeLocation) {
1104 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1106 } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1107 // US ZIP+4 codes - if there is no token,
1108 // merge in the 5-digit ZIP code
1109 if (isset($aValidTokens[$aData[1]])) {
1110 foreach ($aValidTokens[$aData[1]] as $aToken) {
1111 if (!$aToken['class']) {
1112 if (isset($aValidTokens[$sToken])) {
1113 $aValidTokens[$sToken][] = $aToken;
1115 $aValidTokens[$sToken] = array($aToken);
1123 foreach ($aTokens as $sToken) {
1124 // Unknown single word token with a number - assume it is a house number
1125 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1126 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1130 // Any words that have failed completely?
1131 // TODO: suggestions
1133 // Start the search process
1134 // array with: placeid => -1 | tiger-housenumber
1135 $aResultPlaceIDs = array();
1137 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
1139 if ($this->bReverseInPlan) {
1140 // Reverse phrase array and also reverse the order of the wordsets in
1141 // the first and final phrase. Don't bother about phrases in the middle
1142 // because order in the address doesn't matter.
1143 $aPhrases = array_reverse($aPhrases);
1144 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1145 if (sizeof($aPhrases) > 1) {
1146 $aFinalPhrase = end($aPhrases);
1147 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1149 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1151 foreach ($aGroupedSearches as $aSearches) {
1152 foreach ($aSearches as $aSearch) {
1153 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1154 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1155 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1160 $aGroupedSearches = $aReverseGroupedSearches;
1161 ksort($aGroupedSearches);
1164 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1165 $aGroupedSearches = array();
1166 foreach ($aSearches as $aSearch) {
1167 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1168 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1169 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1172 ksort($aGroupedSearches);
1175 if (CONST_Debug) var_Dump($aGroupedSearches);
1176 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1177 $aCopyGroupedSearches = $aGroupedSearches;
1178 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1179 foreach ($aSearches as $iSearch => $aSearch) {
1180 $aReductionsList = array($aSearch['aAddress']);
1181 $iSearchRank = $aSearch['iSearchRank'];
1182 while (sizeof($aReductionsList) > 0) {
1184 if ($iSearchRank > iMaxRank) break 3;
1185 $aNewReductionsList = array();
1186 foreach ($aReductionsList as $aReductionsWordList) {
1187 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1188 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1189 $aReverseSearch = $aSearch;
1190 $aSearch['aAddress'] = $aReductionsWordListResult;
1191 $aSearch['iSearchRank'] = $iSearchRank;
1192 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1193 if (sizeof($aReductionsWordListResult) > 0) {
1194 $aNewReductionsList[] = $aReductionsWordListResult;
1198 $aReductionsList = $aNewReductionsList;
1202 ksort($aGroupedSearches);
1205 // Filter out duplicate searches
1206 $aSearchHash = array();
1207 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1208 foreach ($aSearches as $iSearch => $aSearch) {
1209 $sHash = serialize($aSearch);
1210 if (isset($aSearchHash[$sHash])) {
1211 unset($aGroupedSearches[$iGroup][$iSearch]);
1212 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1214 $aSearchHash[$sHash] = 1;
1219 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1223 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1225 foreach ($aSearches as $aSearch) {
1227 $searchedHousenumber = -1;
1229 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1230 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1232 // No location term?
1233 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon']) {
1234 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1235 // Just looking for a country by code - look it up
1236 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1237 $sSQL = "SELECT place_id FROM placex WHERE calculated_country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1238 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1239 if ($bBoundingBoxSearch)
1240 $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1241 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1242 if (CONST_Debug) var_dump($sSQL);
1243 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1245 $aPlaceIDs = array();
1248 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1249 if (!$aSearch['sClass']) continue;
1251 $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1252 if (chksql($this->oDB->getOne($sSQL))) {
1253 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1254 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1255 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1256 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1257 if (sizeof($this->aExcludePlaceIDs)) {
1258 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1260 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1261 $sSQL .= " limit $this->iLimit";
1262 if (CONST_Debug) var_dump($sSQL);
1263 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1265 // If excluded place IDs are given, it is fair to assume that
1266 // there have been results in the small box, so no further
1267 // expansion in that case.
1268 // Also don't expand if bounded results were requested.
1269 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1270 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1271 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1272 $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1273 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1274 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1275 $sSQL .= " LIMIT $this->iLimit";
1276 if (CONST_Debug) var_dump($sSQL);
1277 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1280 $sSQL = "SELECT place_id ";
1281 $sSQL .= "FROM placex ";
1282 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1283 $sSQL .= " AND type='".$aSearch['sType']."'";
1284 $sSQL .= " AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1285 $sSQL .= " AND linked_place_id is null";
1286 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1287 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1288 $sSQL .= " LIMIT $this->iLimit";
1289 if (CONST_Debug) var_dump($sSQL);
1290 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1293 } elseif ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1294 // If a coordinate is given, the search must either
1295 // be for a name or a special search. Ignore everythin else.
1296 $aPlaceIDs = array();
1298 $aPlaceIDs = array();
1300 // First we need a position, either aName or fLat or both
1304 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1305 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1308 $aOrder[0] .= " EXISTS(";
1309 $aOrder[0] .= " SELECT place_id ";
1310 $aOrder[0] .= " FROM placex ";
1311 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1312 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1313 $aOrder[0] .= " LIMIT 1";
1314 $aOrder[0] .= " ) ";
1315 // also housenumbers from interpolation lines table are needed
1316 $aOrder[0] .= " OR EXISTS(";
1317 $aOrder[0] .= " SELECT place_id ";
1318 $aOrder[0] .= " FROM location_property_osmline ";
1319 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1320 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1321 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1322 $aOrder[0] .= " LIMIT 1";
1325 $aOrder[0] .= " DESC";
1328 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1329 // they might be right - but they are just too darned expensive to run
1330 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1331 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1332 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1333 // For infrequent name terms disable index usage for address
1334 if (CONST_Search_NameOnlySearchFrequencyThreshold
1335 && sizeof($aSearch['aName']) == 1
1336 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1338 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1340 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1341 if (sizeof($aSearch['aAddressNonSearch'])) {
1342 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1346 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1347 if ($aSearch['sHouseNumber']) {
1348 $aTerms[] = "address_rank between 16 and 27";
1350 if ($this->iMinAddressRank > 0) {
1351 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1353 if ($this->iMaxAddressRank < 30) {
1354 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1357 if ($aSearch['fLon'] && $aSearch['fLat']) {
1358 $aTerms[] = sprintf(
1359 'ST_DWithin(centroid, ST_SetSRID(ST_Point(%F,%F),4326), %F)',
1365 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1367 if (sizeof($this->aExcludePlaceIDs)) {
1368 $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1370 if ($sCountryCodesSQL) {
1371 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1374 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1375 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) ASC";
1377 if ($aSearch['sHouseNumber']) {
1378 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1380 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1382 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1383 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1385 $aOrder[] = "$sImportanceSQL DESC";
1386 if (sizeof($aSearch['aFullNameAddress'])) {
1387 $sExactMatchSQL = ' ( ';
1388 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
1389 $sExactMatchSQL .= ' SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1390 $sExactMatchSQL .= ' INTERSECT ';
1391 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
1392 $sExactMatchSQL .= ' ) s';
1393 $sExactMatchSQL .= ') as exactmatch';
1394 $aOrder[] = 'exactmatch DESC';
1396 $sExactMatchSQL = '0::int as exactmatch';
1399 if (sizeof($aTerms)) {
1400 $sSQL = "SELECT place_id, ";
1401 $sSQL .= $sExactMatchSQL;
1402 $sSQL .= " FROM search_name";
1403 $sSQL .= " WHERE ".join(' and ', $aTerms);
1404 $sSQL .= " ORDER BY ".join(', ', $aOrder);
1405 if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1406 $sSQL .= " LIMIT 20";
1407 } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1408 $sSQL .= " LIMIT 1";
1410 $sSQL .= " LIMIT ".$this->iLimit;
1413 if (CONST_Debug) var_dump($sSQL);
1414 $aViewBoxPlaceIDs = chksql(
1415 $this->oDB->getAll($sSQL),
1416 "Could not get places for search terms."
1418 //var_dump($aViewBoxPlaceIDs);
1419 // Did we have an viewbox matches?
1420 $aPlaceIDs = array();
1421 $bViewBoxMatch = false;
1422 foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1423 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1424 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1425 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1426 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1427 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1428 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1431 //var_Dump($aPlaceIDs);
1434 //now search for housenumber, if housenumber provided
1435 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1436 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1437 $aRoadPlaceIDs = $aPlaceIDs;
1438 $sPlaceIDs = join(',', $aPlaceIDs);
1440 // Now they are indexed, look for a house attached to a street we found
1441 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1442 $sSQL = "SELECT place_id FROM placex ";
1443 $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1444 if (sizeof($this->aExcludePlaceIDs)) {
1445 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1447 $sSQL .= " LIMIT $this->iLimit";
1448 if (CONST_Debug) var_dump($sSQL);
1449 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1451 // if nothing found, search in the interpolation line table
1452 if (!sizeof($aPlaceIDs)) {
1453 // do we need to use transliteration and the regex for housenumbers???
1454 //new query for lines, not housenumbers anymore
1455 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1456 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1457 if ($searchedHousenumber%2 == 0) {
1458 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1459 $sSQL .= "interpolationtype='even'";
1461 //look for housenumber in streets with interpolationtype odd or all
1462 $sSQL .= "interpolationtype='odd'";
1464 $sSQL .= " or interpolationtype='all') and ";
1465 $sSQL .= $searchedHousenumber.">=startnumber and ";
1466 $sSQL .= $searchedHousenumber."<=endnumber";
1468 if (sizeof($this->aExcludePlaceIDs)) {
1469 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1471 //$sSQL .= " limit $this->iLimit";
1472 if (CONST_Debug) var_dump($sSQL);
1474 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1477 // If nothing found try the aux fallback table
1478 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1479 $sSQL = "SELECT place_id FROM location_property_aux ";
1480 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1481 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1482 if (sizeof($this->aExcludePlaceIDs)) {
1483 $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1485 //$sSQL .= " limit $this->iLimit";
1486 if (CONST_Debug) var_dump($sSQL);
1487 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1490 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1491 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1492 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1493 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1494 if ($searchedHousenumber%2 == 0) {
1495 $sSQL .= "interpolationtype='even'";
1497 $sSQL .= "interpolationtype='odd'";
1499 $sSQL .= " or interpolationtype='all') and ";
1500 $sSQL .= $searchedHousenumber.">=startnumber and ";
1501 $sSQL .= $searchedHousenumber."<=endnumber";
1503 if (sizeof($this->aExcludePlaceIDs)) {
1504 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1506 //$sSQL .= " limit $this->iLimit";
1507 if (CONST_Debug) var_dump($sSQL);
1509 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1512 // Fallback to the road (if no housenumber was found)
1513 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1514 $aPlaceIDs = $aRoadPlaceIDs;
1515 //set to -1, if no housenumbers were found
1516 $searchedHousenumber = -1;
1518 //else: housenumber was found, remains saved in searchedHousenumber
1522 if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1523 $sPlaceIDs = join(',', $aPlaceIDs);
1524 $aClassPlaceIDs = array();
1526 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1527 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1528 $sSQL = "SELECT place_id ";
1529 $sSQL .= " FROM placex ";
1530 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1531 $sSQL .= " AND class='".$aSearch['sClass']."' ";
1532 $sSQL .= " AND type='".$aSearch['sType']."'";
1533 $sSQL .= " AND linked_place_id is null";
1534 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1535 $sSQL .= " ORDER BY rank_search ASC ";
1536 $sSQL .= " LIMIT $this->iLimit";
1537 if (CONST_Debug) var_dump($sSQL);
1538 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1541 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1542 $sSQL = "SELECT count(*) FROM pg_tables ";
1543 $sSQL .= "WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1544 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1546 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1548 if (CONST_Debug) var_dump($sSQL);
1549 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1551 // For state / country level searches the normal radius search doesn't work very well
1552 $sPlaceGeom = false;
1553 if ($this->iMaxRank < 9 && $bCacheTable) {
1554 // Try and get a polygon to search in instead
1555 $sSQL = "SELECT geometry ";
1556 $sSQL .= " FROM placex";
1557 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1558 $sSQL .= " AND rank_search < $this->iMaxRank + 5";
1559 $sSQL .= " AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1560 $sSQL .= " ORDER BY rank_search ASC ";
1561 $sSQL .= " LIMIT 1";
1562 if (CONST_Debug) var_dump($sSQL);
1563 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1569 $this->iMaxRank += 5;
1570 $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1571 if (CONST_Debug) var_dump($sSQL);
1572 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1573 $sPlaceIDs = join(',', $aPlaceIDs);
1576 if ($sPlaceIDs || $sPlaceGeom) {
1579 // More efficient - can make the range bigger
1583 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1584 elseif ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1585 elseif ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1587 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1588 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1590 $sSQL .= ",placex as f where ";
1591 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1595 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1597 if (sizeof($this->aExcludePlaceIDs)) {
1598 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1600 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1601 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1602 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1603 $sSQL .= " limit $this->iLimit";
1604 if (CONST_Debug) var_dump($sSQL);
1605 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1607 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1610 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1611 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1613 $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1614 $sSQL .= " FROM placex as l, placex as f ";
1615 $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1616 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1617 $sSQL .= " AND l.class='".$aSearch['sClass']."' ";
1618 $sSQL .= " AND l.type='".$aSearch['sType']."' ";
1619 if (sizeof($this->aExcludePlaceIDs)) {
1620 $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1622 if ($sCountryCodesSQL) $sSQL .= " AND l.calculated_country_code in ($sCountryCodesSQL)";
1623 if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1624 if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1625 $sSQL .= " limit $this->iLimit";
1626 if (CONST_Debug) var_dump($sSQL);
1627 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1631 $aPlaceIDs = $aClassPlaceIDs;
1636 echo "<br><b>Place IDs:</b> ";
1637 var_Dump($aPlaceIDs);
1640 foreach ($aPlaceIDs as $iPlaceID) {
1641 // array for placeID => -1 | Tiger housenumber
1642 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1644 if ($iQueryLoop > 20) break;
1647 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1648 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1649 // reduces the number of place ids, like a filter
1650 // rank_address is 30 for interpolated housenumbers
1651 $sSQL = "SELECT place_id ";
1652 $sSQL .= "FROM placex ";
1653 $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1655 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1656 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1657 $sSQL .= " OR (extratags->'place') = 'city'";
1659 if ($this->aAddressRankList) {
1660 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1662 if (CONST_Use_US_Tiger_Data) {
1665 $sSQL .= " SELECT place_id ";
1666 $sSQL .= " FROM location_property_tiger ";
1667 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1668 $sSQL .= " AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1669 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1671 $sSQL .= ") UNION ";
1672 $sSQL .= " SELECT place_id ";
1673 $sSQL .= " FROM location_property_osmline ";
1674 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1675 $sSQL .= " AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1676 if (CONST_Debug) var_dump($sSQL);
1677 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1679 foreach ($aFilteredPlaceIDs as $placeID) {
1680 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1682 $aResultPlaceIDs = $tempIDs;
1686 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1687 if ($iGroupLoop > 4) break;
1688 if ($iQueryLoop > 30) break;
1691 // Did we find anything?
1692 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1693 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1696 // Just interpret as a reverse geocode
1697 $oReverse = new ReverseGeocode($this->oDB);
1698 $oReverse->setZoom(18);
1700 $aLookup = $oReverse->lookup(
1701 (float)$this->aNearPoint[0],
1702 (float)$this->aNearPoint[1],
1706 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1708 if ($aLookup['place_id']) {
1709 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1710 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1712 $aSearchResults = array();
1717 if (!sizeof($aSearchResults)) {
1718 if ($this->bFallback) {
1719 if ($this->fallbackStructuredQuery()) {
1720 return $this->lookup();
1727 $aClassType = getClassTypesWithImportance();
1728 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1729 foreach ($aRecheckWords as $i => $sWord) {
1730 if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1734 echo '<i>Recheck words:<\i>';
1735 var_dump($aRecheckWords);
1738 $oPlaceLookup = new PlaceLookup($this->oDB);
1739 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1740 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1741 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1742 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1743 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1744 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1746 foreach ($aSearchResults as $iResNum => $aResult) {
1748 $fDiameter = getResultDiameter($aResult);
1750 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1751 if ($aOutlineResult) {
1752 $aResult = array_merge($aResult, $aOutlineResult);
1755 if ($aResult['extra_place'] == 'city') {
1756 $aResult['class'] = 'place';
1757 $aResult['type'] = 'city';
1758 $aResult['rank_search'] = 16;
1761 // Is there an icon set for this type of result?
1762 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1763 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1765 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1768 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1769 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1771 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1772 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1773 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1775 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1777 // if tag '&addressdetails=1' is set in query
1778 if ($this->bIncludeAddressDetails) {
1779 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1780 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1781 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1782 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1786 if ($this->bIncludeExtraTags) {
1787 if ($aResult['extra']) {
1788 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1790 $aResult['sExtraTags'] = (object) array();
1794 if ($this->bIncludeNameDetails) {
1795 if ($aResult['names']) {
1796 $aResult['sNameDetails'] = json_decode($aResult['names']);
1798 $aResult['sNameDetails'] = (object) array();
1802 // Adjust importance for the number of exact string matches in the result
1803 $aResult['importance'] = max(0.001, $aResult['importance']);
1805 $sAddress = $aResult['langaddress'];
1806 foreach ($aRecheckWords as $i => $sWord) {
1807 if (stripos($sAddress, $sWord)!==false) {
1809 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1813 $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
1815 $aResult['name'] = $aResult['langaddress'];
1816 // secondary ordering (for results with same importance (the smaller the better):
1817 // - approximate importance of address parts
1818 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1819 // - number of exact matches from the query
1820 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1821 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1822 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1823 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1825 // - importance of the class/type
1826 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1827 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1829 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1831 $aResult['foundorder'] += 0.01;
1833 if (CONST_Debug) var_dump($aResult);
1834 $aSearchResults[$iResNum] = $aResult;
1836 uasort($aSearchResults, 'byImportance');
1838 $aOSMIDDone = array();
1839 $aClassTypeNameDone = array();
1840 $aToFilter = $aSearchResults;
1841 $aSearchResults = array();
1844 foreach ($aToFilter as $iResNum => $aResult) {
1845 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1847 $fLat = $aResult['lat'];
1848 $fLon = $aResult['lon'];
1849 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1852 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1853 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1855 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1856 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1857 $aSearchResults[] = $aResult;
1860 // Absolute limit on number of results
1861 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1864 return $aSearchResults;