6 protected $aLangPrefOrder = array();
8 protected $bIncludeAddressDetails = false;
10 protected $bIncludePolygonAsPoints = false;
11 protected $bIncludePolygonAsText = false;
12 protected $bIncludePolygonAsGeoJSON = false;
13 protected $bIncludePolygonAsKML = false;
14 protected $bIncludePolygonAsSVG = false;
16 protected $aExcludePlaceIDs = array();
17 protected $bDeDupe = true;
18 protected $bReverseInPlan = false;
20 protected $iLimit = 20;
21 protected $iFinalLimit = 10;
22 protected $iOffset = 0;
23 protected $bFallback = false;
25 protected $aCountryCodes = false;
26 protected $aNearPoint = false;
28 protected $bBoundedSearch = false;
29 protected $aViewBox = false;
30 protected $aRoutePoints = false;
32 protected $iMaxRank = 20;
33 protected $iMinAddressRank = 0;
34 protected $iMaxAddressRank = 30;
35 protected $aAddressRankList = array();
36 protected $exactMatchCache = array();
38 protected $sAllowedTypesSQLList = false;
40 protected $sQuery = false;
41 protected $aStructuredQuery = false;
43 function Geocode(&$oDB)
48 function setReverseInPlan($bReverse)
50 $this->bReverseInPlan = $bReverse;
53 function setLanguagePreference($aLangPref)
55 $this->aLangPrefOrder = $aLangPref;
58 function setIncludeAddressDetails($bAddressDetails = true)
60 $this->bIncludeAddressDetails = (bool)$bAddressDetails;
63 function getIncludeAddressDetails()
65 return $this->bIncludeAddressDetails;
68 function setIncludePolygonAsPoints($b = true)
70 $this->bIncludePolygonAsPoints = $b;
73 function getIncludePolygonAsPoints()
75 return $this->bIncludePolygonAsPoints;
78 function setIncludePolygonAsText($b = true)
80 $this->bIncludePolygonAsText = $b;
83 function getIncludePolygonAsText()
85 return $this->bIncludePolygonAsText;
88 function setIncludePolygonAsGeoJSON($b = true)
90 $this->bIncludePolygonAsGeoJSON = $b;
93 function setIncludePolygonAsKML($b = true)
95 $this->bIncludePolygonAsKML = $b;
98 function setIncludePolygonAsSVG($b = true)
100 $this->bIncludePolygonAsSVG = $b;
103 function setDeDupe($bDeDupe = true)
105 $this->bDeDupe = (bool)$bDeDupe;
108 function setLimit($iLimit = 10)
110 if ($iLimit > 50) $iLimit = 50;
111 if ($iLimit < 1) $iLimit = 1;
113 $this->iFinalLimit = $iLimit;
114 $this->iLimit = $this->iFinalLimit + min($this->iFinalLimit, 10);
117 function setOffset($iOffset = 0)
119 $this->iOffset = $iOffset;
122 function setFallback($bFallback = true)
124 $this->bFallback = (bool)$bFallback;
127 function setExcludedPlaceIDs($a)
129 // TODO: force to int
130 $this->aExcludePlaceIDs = $a;
133 function getExcludedPlaceIDs()
135 return $this->aExcludePlaceIDs;
138 function setBounded($bBoundedSearch = true)
140 $this->bBoundedSearch = (bool)$bBoundedSearch;
143 function setViewBox($fLeft, $fBottom, $fRight, $fTop)
145 $this->aViewBox = array($fLeft, $fBottom, $fRight, $fTop);
148 function getViewBoxString()
150 if (!$this->aViewBox) return null;
151 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
154 function setRoute($aRoutePoints)
156 $this->aRoutePoints = $aRoutePoints;
159 function setFeatureType($sFeatureType)
161 switch($sFeatureType)
164 $this->setRankRange(4, 4);
167 $this->setRankRange(8, 8);
170 $this->setRankRange(14, 16);
173 $this->setRankRange(8, 20);
178 function setRankRange($iMin, $iMax)
180 $this->iMinAddressRank = (int)$iMin;
181 $this->iMaxAddressRank = (int)$iMax;
184 function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
186 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
189 function setCountryCodesList($aCountryCodes)
191 $this->aCountryCodes = $aCountryCodes;
194 function setQuery($sQueryString)
196 $this->sQuery = $sQueryString;
197 $this->aStructuredQuery = false;
200 function getQueryString()
202 return $this->sQuery;
205 function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
207 $sValue = trim($sValue);
208 if (!$sValue) return false;
209 $this->aStructuredQuery[$sKey] = $sValue;
210 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30)
212 $this->iMinAddressRank = $iNewMinAddressRank;
213 $this->iMaxAddressRank = $iNewMaxAddressRank;
215 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
219 function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
221 $this->sQuery = false;
224 $this->iMinAddressRank = 0;
225 $this->iMaxAddressRank = 30;
226 $this->aAddressRankList = array();
228 $this->aStructuredQuery = array();
229 $this->sAllowedTypesSQLList = '';
231 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
232 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
233 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
234 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
235 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
236 $this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11));
237 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
239 if (sizeof($this->aStructuredQuery) > 0)
241 $this->sQuery = join(', ', $this->aStructuredQuery);
242 if ($this->iMaxAddressRank < 30)
244 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
249 function fallbackStructuredQuery()
251 if (!$this->aStructuredQuery) return false;
253 $aParams = $this->aStructuredQuery;
255 if (sizeof($aParams) == 1) return false;
257 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
259 foreach($aOrderToFallback as $sType)
261 if (isset($aParams[$sType]))
263 unset($aParams[$sType]);
264 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
272 function getDetails($aPlaceIDs)
274 if (sizeof($aPlaceIDs) == 0) return array();
276 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
278 // Get the details for display (is this a redundant extra step?)
279 $sPlaceIDs = join(',',$aPlaceIDs);
281 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id, calculated_country_code as country_code,";
282 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
283 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
284 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
285 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
286 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
287 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
288 $sSQL .= "(extratags->'place') as extra_place ";
289 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
290 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
291 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
292 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
294 if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
295 $sSQL .= "and linked_place_id is null ";
296 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
297 if (!$this->bDeDupe) $sSQL .= ",place_id";
298 $sSQL .= ",langaddress ";
299 $sSQL .= ",placename ";
301 $sSQL .= ",extratags->'place' ";
303 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
306 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id,'us' as country_code,";
307 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
308 $sSQL .= "null as placename,";
309 $sSQL .= "null as ref,";
310 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
311 $sSQL .= "-0.15 as importance, ";
312 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_tiger.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
313 $sSQL .= "null as extra_place ";
314 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
315 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
316 $sSQL .= "group by place_id";
317 if (!$this->bDeDupe) $sSQL .= ",place_id";
319 $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id,'us' as country_code,";
320 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
321 $sSQL .= "null as placename,";
322 $sSQL .= "null as ref,";
323 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
324 $sSQL .= "-0.10 as importance, ";
325 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
326 $sSQL .= "null as extra_place ";
327 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
328 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
329 $sSQL .= "group by place_id";
330 if (!$this->bDeDupe) $sSQL .= ",place_id";
331 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
334 $sSQL .= "order by importance desc";
335 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
336 $aSearchResults = $this->oDB->getAll($sSQL);
338 if (PEAR::IsError($aSearchResults))
340 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
343 return $aSearchResults;
346 /* Perform the actual query lookup.
348 Returns an ordered list of results, each with the following fields:
349 osm_type: type of corresponding OSM object
353 P - postcode (internally computed)
354 osm_id: id of corresponding OSM object
355 class: general object class (corresponds to tag key of primary OSM tag)
356 type: subclass of object (corresponds to tag value of primary OSM tag)
357 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
358 rank_search: rank in search hierarchy
359 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
360 rank_address: rank in address hierarchy (determines orer in address)
361 place_id: internal key (may differ between different instances)
362 country_code: ISO country code
363 langaddress: localized full address
364 placename: localized name of object
365 ref: content of ref tag (if available)
368 importance: importance of place based on Wikipedia link count
369 addressimportance: cumulated importance of address elements
370 extra_place: type of place (for admin boundaries, if there is a place tag)
371 aBoundingBox: bounding Box
372 label: short description of the object class/type (English only)
373 name: full name (currently the same as langaddress)
374 foundorder: secondary ordering for places with same importance
378 if (!$this->sQuery && !$this->aStructuredQuery) return false;
380 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
382 $sCountryCodesSQL = false;
383 if ($this->aCountryCodes && sizeof($this->aCountryCodes))
385 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
388 // Hack to make it handle "new york, ny" (and variants) correctly
389 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $this->sQuery);
391 // Conflicts between US state abreviations and various words for 'the' in different languages
392 if (isset($this->aLangPrefOrder['name:en']))
394 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
395 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
396 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
400 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
401 $bBoundingBoxSearch = false;
404 $fHeight = $this->aViewBox[0]-$this->aViewBox[2];
405 $fWidth = $this->aViewBox[1]-$this->aViewBox[3];
406 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
407 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
408 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
409 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
411 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$this->aViewBox[0].",".(float)$this->aViewBox[1]."),ST_Point(".(float)$this->aViewBox[2].",".(float)$this->aViewBox[3].")),4326)";
412 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aBigViewBox[0].",".(float)$aBigViewBox[1]."),ST_Point(".(float)$aBigViewBox[2].",".(float)$aBigViewBox[3].")),4326)";
413 $bBoundingBoxSearch = $this->bBoundedSearch;
417 if ($this->aRoutePoints)
419 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
421 foreach($this->aRouteaPoints as $aPoint)
423 if (!$bFirst) $sViewboxCentreSQL .= ",";
424 $sViewboxCentreSQL .= $aPoint[1].' '.$aPoint[0];
426 $sViewboxCentreSQL .= ")'::geometry,4326)";
428 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
429 $sViewboxSmallSQL = $this->oDB->getOne($sSQL);
430 if (PEAR::isError($sViewboxSmallSQL))
432 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
434 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
436 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
437 $sViewboxLargeSQL = $this->oDB->getOne($sSQL);
438 if (PEAR::isError($sViewboxLargeSQL))
440 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
442 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
443 $bBoundingBoxSearch = $this->bBoundedSearch;
446 // Do we have anything that looks like a lat/lon pair?
447 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
449 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
450 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
451 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
453 $this->setNearPoint(array($fQueryLat, $fQueryLon));
454 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
457 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
459 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
460 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
461 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
463 $this->setNearPoint(array($fQueryLat, $fQueryLon));
464 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
467 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData))
469 $fQueryLat = $aData[2];
470 $fQueryLon = $aData[3];
471 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
473 $this->setNearPoint(array($fQueryLat, $fQueryLon));
474 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
478 $aSearchResults = array();
479 if ($sQuery || $this->aStructuredQuery)
481 // Start with a blank search
483 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
484 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
485 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
488 // Do we have a radius search?
489 $sNearPointSQL = false;
490 if ($this->aNearPoint)
492 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
493 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
494 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
495 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
498 // Any 'special' terms in the search?
499 $bSpecialTerms = false;
500 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
501 $aSpecialTerms = array();
502 foreach($aSpecialTermsRaw as $aSpecialTerm)
504 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
505 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
508 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
509 $aSpecialTerms = array();
510 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
512 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
513 unset($aStructuredQuery['amenity']);
515 foreach($aSpecialTermsRaw as $aSpecialTerm)
517 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
518 $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
519 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
520 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
521 if (CONST_Debug) var_Dump($sSQL);
522 $aSearchWords = $this->oDB->getAll($sSQL);
523 $aNewSearches = array();
524 foreach($aSearches as $aSearch)
526 foreach($aSearchWords as $aSearchTerm)
528 $aNewSearch = $aSearch;
529 if ($aSearchTerm['country_code'])
531 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
532 $aNewSearches[] = $aNewSearch;
533 $bSpecialTerms = true;
535 if ($aSearchTerm['class'])
537 $aNewSearch['sClass'] = $aSearchTerm['class'];
538 $aNewSearch['sType'] = $aSearchTerm['type'];
539 $aNewSearches[] = $aNewSearch;
540 $bSpecialTerms = true;
544 $aSearches = $aNewSearches;
547 // Split query into phrases
548 // Commas are used to reduce the search space by indicating where phrases split
549 if ($this->aStructuredQuery)
551 $aPhrases = $this->aStructuredQuery;
552 $bStructuredPhrases = true;
556 $aPhrases = explode(',',$sQuery);
557 $bStructuredPhrases = false;
560 // Convert each phrase to standard form
561 // Create a list of standard words
562 // Get all 'sets' of words
563 // Generate a complete list of all
565 foreach($aPhrases as $iPhrase => $sPhrase)
567 $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
568 if (PEAR::isError($aPhrase))
570 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
571 if (CONST_Debug) var_dump($aPhrase);
574 if (trim($aPhrase['string']))
576 $aPhrases[$iPhrase] = $aPhrase;
577 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
578 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
579 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
583 unset($aPhrases[$iPhrase]);
587 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
588 $aPhraseTypes = array_keys($aPhrases);
589 $aPhrases = array_values($aPhrases);
591 if (sizeof($aTokens))
593 // Check which tokens we have, get the ID numbers
594 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
595 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
597 if (CONST_Debug) var_Dump($sSQL);
599 $aValidTokens = array();
600 if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL);
601 else $aDatabaseWords = array();
602 if (PEAR::IsError($aDatabaseWords))
604 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
606 $aPossibleMainWordIDs = array();
607 $aWordFrequencyScores = array();
608 foreach($aDatabaseWords as $aToken)
610 // Very special case - require 2 letter country param to match the country code found
611 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
612 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
617 if (isset($aValidTokens[$aToken['word_token']]))
619 $aValidTokens[$aToken['word_token']][] = $aToken;
623 $aValidTokens[$aToken['word_token']] = array($aToken);
625 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
626 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
628 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
630 // Try and calculate GB postcodes we might be missing
631 foreach($aTokens as $sToken)
633 // Source of gb postcodes is now definitive - always use
634 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
636 if (substr($aData[1],-2,1) != ' ')
638 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
639 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
641 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
642 if ($aGBPostcodeLocation)
644 $aValidTokens[$sToken] = $aGBPostcodeLocation;
647 // US ZIP+4 codes - if there is no token,
648 // merge in the 5-digit ZIP code
649 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
651 if (isset($aValidTokens[$aData[1]]))
653 foreach($aValidTokens[$aData[1]] as $aToken)
655 if (!$aToken['class'])
657 if (isset($aValidTokens[$sToken]))
659 $aValidTokens[$sToken][] = $aToken;
663 $aValidTokens[$sToken] = array($aToken);
671 foreach($aTokens as $sToken)
673 // Unknown single word token with a number - assume it is a house number
674 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
676 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
680 // Any words that have failed completely?
683 // Start the search process
684 $aResultPlaceIDs = array();
687 Calculate all searches using aValidTokens i.e.
688 'Wodsworth Road, Sheffield' =>
692 0 1 (wodsworth)(road)
695 Score how good the search is so they can be ordered
697 foreach($aPhrases as $iPhrase => $sPhrase)
699 $aNewPhraseSearches = array();
700 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
701 else $sPhraseType = '';
703 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
705 // Too many permutations - too expensive
706 if ($iWordSet > 120) break;
708 $aWordsetSearches = $aSearches;
710 // Add all words from this wordset
711 foreach($aWordset as $iToken => $sToken)
713 //echo "<br><b>$sToken</b>";
714 $aNewWordsetSearches = array();
716 foreach($aWordsetSearches as $aCurrentSearch)
719 //var_dump($aCurrentSearch);
722 // If the token is valid
723 if (isset($aValidTokens[' '.$sToken]))
725 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
727 $aSearch = $aCurrentSearch;
728 $aSearch['iSearchRank']++;
729 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
731 if ($aSearch['sCountryCode'] === false)
733 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
734 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
735 // If reverse order is enabled, it may appear at the beginning as well.
736 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
737 (!$this->bReverseInPlan || $iToken > 0 || $iPhrase > 0))
739 $aSearch['iSearchRank'] += 5;
741 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
744 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
746 if ($aSearch['fLat'] === '')
748 $aSearch['fLat'] = $aSearchTerm['lat'];
749 $aSearch['fLon'] = $aSearchTerm['lon'];
750 $aSearch['fRadius'] = $aSearchTerm['radius'];
751 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
754 elseif ($sPhraseType == 'postalcode')
756 // 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
757 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
759 // If we already have a name try putting the postcode first
760 if (sizeof($aSearch['aName']))
762 $aNewSearch = $aSearch;
763 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
764 $aNewSearch['aName'] = array();
765 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
766 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
769 if (sizeof($aSearch['aName']))
771 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
773 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
777 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
778 $aSearch['iSearchRank'] += 1000; // skip;
783 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
784 //$aSearch['iNamePhrase'] = $iPhrase;
786 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
790 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
792 if ($aSearch['sHouseNumber'] === '')
794 $aSearch['sHouseNumber'] = $sToken;
795 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
797 // Fall back to not searching for this item (better than nothing)
798 $aSearch = $aCurrentSearch;
799 $aSearch['iSearchRank'] += 1;
800 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
804 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
806 if ($aSearch['sClass'] === '')
808 $aSearch['sOperator'] = $aSearchTerm['operator'];
809 $aSearch['sClass'] = $aSearchTerm['class'];
810 $aSearch['sType'] = $aSearchTerm['type'];
811 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
812 else $aSearch['sOperator'] = 'near'; // near = in for the moment
814 // Do we have a shortcut id?
815 if ($aSearch['sOperator'] == 'name')
817 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
818 if ($iAmenityID = $this->oDB->getOne($sSQL))
820 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
821 $aSearch['aName'][$iAmenityID] = $iAmenityID;
822 $aSearch['sClass'] = '';
823 $aSearch['sType'] = '';
826 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
829 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
831 if (sizeof($aSearch['aName']))
833 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
835 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
839 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
840 $aSearch['iSearchRank'] += 1000; // skip;
845 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
846 //$aSearch['iNamePhrase'] = $iPhrase;
848 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
852 if (isset($aValidTokens[$sToken]))
854 // Allow searching for a word - but at extra cost
855 foreach($aValidTokens[$sToken] as $aSearchTerm)
857 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
859 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
861 $aSearch = $aCurrentSearch;
862 $aSearch['iSearchRank'] += 1;
863 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
865 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
866 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
868 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
870 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
872 if (empty($aSearchTermToken['country_code'])
873 && empty($aSearchTermToken['lat'])
874 && empty($aSearchTermToken['class']))
876 $aSearch = $aCurrentSearch;
877 $aSearch['iSearchRank'] += 1;
878 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
879 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
885 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
886 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
890 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
892 $aSearch = $aCurrentSearch;
893 $aSearch['iSearchRank'] += 2;
894 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
895 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
896 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
898 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
899 $aSearch['iNamePhrase'] = $iPhrase;
900 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
907 // Allow skipping a word - but at EXTREAM cost
908 //$aSearch = $aCurrentSearch;
909 //$aSearch['iSearchRank']+=100;
910 //$aNewWordsetSearches[] = $aSearch;
914 usort($aNewWordsetSearches, 'bySearchRank');
915 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
917 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
919 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
920 usort($aNewPhraseSearches, 'bySearchRank');
922 $aSearchHash = array();
923 foreach($aNewPhraseSearches as $iSearch => $aSearch)
925 $sHash = serialize($aSearch);
926 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
927 else $aSearchHash[$sHash] = 1;
930 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
933 // Re-group the searches by their score, junk anything over 20 as just not worth trying
934 $aGroupedSearches = array();
935 foreach($aNewPhraseSearches as $aSearch)
937 if ($aSearch['iSearchRank'] < $this->iMaxRank)
939 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
940 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
943 ksort($aGroupedSearches);
946 $aSearches = array();
947 foreach($aGroupedSearches as $iScore => $aNewSearches)
949 $iSearchCount += sizeof($aNewSearches);
950 $aSearches = array_merge($aSearches, $aNewSearches);
951 if ($iSearchCount > 50) break;
954 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
961 // Re-group the searches by their score, junk anything over 20 as just not worth trying
962 $aGroupedSearches = array();
963 foreach($aSearches as $aSearch)
965 if ($aSearch['iSearchRank'] < $this->iMaxRank)
967 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
968 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
971 ksort($aGroupedSearches);
974 if (CONST_Debug) var_Dump($aGroupedSearches);
976 if ($this->bReverseInPlan)
978 $aCopyGroupedSearches = $aGroupedSearches;
979 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
981 foreach($aSearches as $iSearch => $aSearch)
983 if (sizeof($aSearch['aAddress']))
985 $iReverseItem = array_pop($aSearch['aAddress']);
986 if (isset($aPossibleMainWordIDs[$iReverseItem]))
988 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
989 $aSearch['aName'] = array($iReverseItem);
990 $aGroupedSearches[$iGroup][] = $aSearch;
992 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
993 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
999 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
1001 $aCopyGroupedSearches = $aGroupedSearches;
1002 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
1004 foreach($aSearches as $iSearch => $aSearch)
1006 $aReductionsList = array($aSearch['aAddress']);
1007 $iSearchRank = $aSearch['iSearchRank'];
1008 while(sizeof($aReductionsList) > 0)
1011 if ($iSearchRank > iMaxRank) break 3;
1012 $aNewReductionsList = array();
1013 foreach($aReductionsList as $aReductionsWordList)
1015 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
1017 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1018 $aReverseSearch = $aSearch;
1019 $aSearch['aAddress'] = $aReductionsWordListResult;
1020 $aSearch['iSearchRank'] = $iSearchRank;
1021 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1022 if (sizeof($aReductionsWordListResult) > 0)
1024 $aNewReductionsList[] = $aReductionsWordListResult;
1028 $aReductionsList = $aNewReductionsList;
1032 ksort($aGroupedSearches);
1035 // Filter out duplicate searches
1036 $aSearchHash = array();
1037 foreach($aGroupedSearches as $iGroup => $aSearches)
1039 foreach($aSearches as $iSearch => $aSearch)
1041 $sHash = serialize($aSearch);
1042 if (isset($aSearchHash[$sHash]))
1044 unset($aGroupedSearches[$iGroup][$iSearch]);
1045 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1049 $aSearchHash[$sHash] = 1;
1054 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1058 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
1061 foreach($aSearches as $aSearch)
1065 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
1066 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1068 // No location term?
1069 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
1071 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
1073 // Just looking for a country by code - look it up
1074 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
1076 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1077 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1078 $sSQL .= " order by st_area(geometry) desc limit 1";
1079 if (CONST_Debug) var_dump($sSQL);
1080 $aPlaceIDs = $this->oDB->getCol($sSQL);
1085 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1086 if (!$aSearch['sClass']) continue;
1087 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1088 if ($this->oDB->getOne($sSQL))
1090 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1091 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1092 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
1093 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1094 if (sizeof($this->aExcludePlaceIDs))
1096 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1098 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1099 $sSQL .= " limit $this->iLimit";
1100 if (CONST_Debug) var_dump($sSQL);
1101 $aPlaceIDs = $this->oDB->getCol($sSQL);
1103 // If excluded place IDs are given, it is fair to assume that
1104 // there have been results in the small box, so no further
1105 // expansion in that case.
1106 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs))
1108 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1109 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1110 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
1111 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1112 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1113 $sSQL .= " limit $this->iLimit";
1114 if (CONST_Debug) var_dump($sSQL);
1115 $aPlaceIDs = $this->oDB->getCol($sSQL);
1120 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1121 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
1122 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1123 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
1124 $sSQL .= " limit $this->iLimit";
1125 if (CONST_Debug) var_dump($sSQL);
1126 $aPlaceIDs = $this->oDB->getCol($sSQL);
1132 $aPlaceIDs = array();
1134 // First we need a position, either aName or fLat or both
1138 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1139 // they might be right - but they are just too darned expensive to run
1140 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
1141 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
1142 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
1144 // For infrequent name terms disable index usage for address
1145 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
1146 sizeof($aSearch['aName']) == 1 &&
1147 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
1149 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
1153 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
1154 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
1157 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1158 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
1159 if ($aSearch['fLon'] && $aSearch['fLat'])
1161 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1162 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1164 if (sizeof($this->aExcludePlaceIDs))
1166 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1168 if ($sCountryCodesSQL)
1170 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1173 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
1174 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1176 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1177 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1178 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1179 $aOrder[] = "$sImportanceSQL DESC";
1180 if (sizeof($aSearch['aFullNameAddress']))
1182 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1183 $aOrder[] = 'exactmatch DESC';
1185 $sExactMatchSQL = '0::int as exactmatch';
1188 if (sizeof($aTerms))
1190 $sSQL = "select place_id, ";
1191 $sSQL .= $sExactMatchSQL;
1192 $sSQL .= " from search_name";
1193 $sSQL .= " where ".join(' and ',$aTerms);
1194 $sSQL .= " order by ".join(', ',$aOrder);
1195 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
1196 $sSQL .= " limit 50";
1197 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
1198 $sSQL .= " limit 1";
1200 $sSQL .= " limit ".$this->iLimit;
1202 if (CONST_Debug) { var_dump($sSQL); }
1203 $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL);
1204 if (PEAR::IsError($aViewBoxPlaceIDs))
1206 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
1208 //var_dump($aViewBoxPlaceIDs);
1209 // Did we have an viewbox matches?
1210 $aPlaceIDs = array();
1211 $bViewBoxMatch = false;
1212 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
1214 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1215 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1216 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1217 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1218 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1219 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1222 //var_Dump($aPlaceIDs);
1225 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1227 $aRoadPlaceIDs = $aPlaceIDs;
1228 $sPlaceIDs = join(',',$aPlaceIDs);
1230 // Now they are indexed look for a house attached to a street we found
1231 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1232 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1233 if (sizeof($this->aExcludePlaceIDs))
1235 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1237 $sSQL .= " limit $this->iLimit";
1238 if (CONST_Debug) var_dump($sSQL);
1239 $aPlaceIDs = $this->oDB->getCol($sSQL);
1241 // If not try the aux fallback table
1242 if (!sizeof($aPlaceIDs))
1244 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1245 if (sizeof($this->aExcludePlaceIDs))
1247 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1249 //$sSQL .= " limit $this->iLimit";
1250 if (CONST_Debug) var_dump($sSQL);
1251 $aPlaceIDs = $this->oDB->getCol($sSQL);
1254 if (!sizeof($aPlaceIDs))
1256 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1257 if (sizeof($this->aExcludePlaceIDs))
1259 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1261 //$sSQL .= " limit $this->iLimit";
1262 if (CONST_Debug) var_dump($sSQL);
1263 $aPlaceIDs = $this->oDB->getCol($sSQL);
1266 // Fallback to the road
1267 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1269 $aPlaceIDs = $aRoadPlaceIDs;
1274 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1276 $sPlaceIDs = join(',',$aPlaceIDs);
1277 $aClassPlaceIDs = array();
1279 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1281 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1282 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1283 $sSQL .= " and linked_place_id is null";
1284 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1285 $sSQL .= " order by rank_search asc limit $this->iLimit";
1286 if (CONST_Debug) var_dump($sSQL);
1287 $aClassPlaceIDs = $this->oDB->getCol($sSQL);
1290 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1292 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1293 $bCacheTable = $this->oDB->getOne($sSQL);
1295 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1297 if (CONST_Debug) var_dump($sSQL);
1298 $this->iMaxRank = ((int)$this->oDB->getOne($sSQL));
1300 // For state / country level searches the normal radius search doesn't work very well
1301 $sPlaceGeom = false;
1302 if ($this->iMaxRank < 9 && $bCacheTable)
1304 // Try and get a polygon to search in instead
1305 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
1306 if (CONST_Debug) var_dump($sSQL);
1307 $sPlaceGeom = $this->oDB->getOne($sSQL);
1316 $this->iMaxRank += 5;
1317 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1318 if (CONST_Debug) var_dump($sSQL);
1319 $aPlaceIDs = $this->oDB->getCol($sSQL);
1320 $sPlaceIDs = join(',',$aPlaceIDs);
1323 if ($sPlaceIDs || $sPlaceGeom)
1329 // More efficient - can make the range bigger
1333 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1334 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1335 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1337 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1338 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1341 $sSQL .= ",placex as f where ";
1342 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1347 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1349 if (sizeof($this->aExcludePlaceIDs))
1351 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1353 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1354 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1355 if ($iOffset) $sSQL .= " offset $iOffset";
1356 $sSQL .= " limit $this->iLimit";
1357 if (CONST_Debug) var_dump($sSQL);
1358 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1362 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1365 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1366 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1368 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1369 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1370 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1371 if (sizeof($this->aExcludePlaceIDs))
1373 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1375 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1376 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1377 if ($iOffset) $sSQL .= " offset $iOffset";
1378 $sSQL .= " limit $this->iLimit";
1379 if (CONST_Debug) var_dump($sSQL);
1380 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1385 $aPlaceIDs = $aClassPlaceIDs;
1391 if (PEAR::IsError($aPlaceIDs))
1393 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1396 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1398 foreach($aPlaceIDs as $iPlaceID)
1400 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1402 if ($iQueryLoop > 20) break;
1405 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
1407 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1408 $sSQL = "select place_id from placex where place_id in (".join(',',$aResultPlaceIDs).") ";
1409 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1410 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1411 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
1412 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',$aResultPlaceIDs).") ";
1413 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1414 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
1416 if (CONST_Debug) var_dump($sSQL);
1417 $aResultPlaceIDs = $this->oDB->getCol($sSQL);
1421 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1422 if ($iGroupLoop > 4) break;
1423 if ($iQueryLoop > 30) break;
1426 // Did we find anything?
1427 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1429 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1435 // Just interpret as a reverse geocode
1436 $iPlaceID = geocodeReverse((float)$this->aNearPoint[0], (float)$this->aNearPoint[1]);
1438 $aSearchResults = $this->getDetails(array($iPlaceID));
1440 $aSearchResults = array();
1444 if (!sizeof($aSearchResults))
1446 if ($this->bFallback)
1448 if ($this->fallbackStructuredQuery())
1450 return $this->lookup();
1457 $aClassType = getClassTypesWithImportance();
1458 $aRecheckWords = preg_split('/\b/u',$sQuery);
1459 foreach($aRecheckWords as $i => $sWord)
1461 if (!$sWord) unset($aRecheckWords[$i]);
1464 foreach($aSearchResults as $iResNum => $aResult)
1466 if (CONST_Search_AreaPolygons)
1468 // Get the bounding box and outline polygon
1469 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1470 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1471 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1472 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1473 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1474 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1475 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1476 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
1477 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1478 $aPointPolygon = $this->oDB->getRow($sSQL);
1479 if (PEAR::IsError($aPointPolygon))
1481 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1484 if ($aPointPolygon['place_id'])
1486 if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1487 if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1488 if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1489 if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
1491 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1493 $aResult['lat'] = $aPointPolygon['centrelat'];
1494 $aResult['lon'] = $aPointPolygon['centrelon'];
1497 if ($this->bIncludePolygonAsPoints)
1499 // Translate geometary string to point array
1500 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1502 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1504 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1506 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1508 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1511 $iSteps = ($fRadius * 40000)^2;
1512 $fStepSize = (2*pi())/$iSteps;
1513 $aPolyPoints = array();
1514 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1516 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1518 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1519 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1520 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1521 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1525 // Output data suitable for display (points and a bounding box)
1526 if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
1528 $aResult['aPolyPoints'] = array();
1529 foreach($aPolyPoints as $aPoint)
1531 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1534 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1538 if ($aResult['extra_place'] == 'city')
1540 $aResult['class'] = 'place';
1541 $aResult['type'] = 'city';
1542 $aResult['rank_search'] = 16;
1545 if (!isset($aResult['aBoundingBox']))
1548 $fDiameter = 0.0001;
1550 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1551 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1553 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1555 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1556 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1558 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1560 $fRadius = $fDiameter / 2;
1562 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1563 $fStepSize = (2*pi())/$iSteps;
1564 $aPolyPoints = array();
1565 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1567 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1569 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1570 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1571 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1572 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1574 // Output data suitable for display (points and a bounding box)
1575 if ($this->bIncludePolygonAsPoints)
1577 $aResult['aPolyPoints'] = array();
1578 foreach($aPolyPoints as $aPoint)
1580 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1583 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1586 // Is there an icon set for this type of result?
1587 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1588 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1590 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1593 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1594 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1596 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1598 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1599 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1601 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1604 if ($this->bIncludeAddressDetails)
1606 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1607 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1609 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1613 // Adjust importance for the number of exact string matches in the result
1614 $aResult['importance'] = max(0.001,$aResult['importance']);
1616 $sAddress = $aResult['langaddress'];
1617 foreach($aRecheckWords as $i => $sWord)
1619 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1622 $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
1624 $aResult['name'] = $aResult['langaddress'];
1625 // secondary ordering (for results with same importance (the smaller the better):
1626 // - approximate importance of address parts
1627 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1628 // - number of exact matches from the query
1629 if (isset($this->exactMatchCache[$aResult['place_id']]))
1630 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1631 else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
1632 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1633 // - importance of the class/type
1634 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1635 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1637 $aResult['foundorder'] = $aResult['foundorder'] + 0.000001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1641 $aResult['foundorder'] = $aResult['foundorder'] + 0.001;
1643 $aSearchResults[$iResNum] = $aResult;
1645 uasort($aSearchResults, 'byImportance');
1647 $aOSMIDDone = array();
1648 $aClassTypeNameDone = array();
1649 $aToFilter = $aSearchResults;
1650 $aSearchResults = array();
1653 foreach($aToFilter as $iResNum => $aResult)
1655 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1656 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1659 $fLat = $aResult['lat'];
1660 $fLon = $aResult['lon'];
1661 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1664 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1665 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1667 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1668 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1669 $aSearchResults[] = $aResult;
1672 // Absolute limit on number of results
1673 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1676 return $aSearchResults;
1685 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
1687 $aPoints = explode(',',$_GET['route']);
1688 if (sizeof($aPoints) % 2 != 0)
1690 userError("Uneven number of points");
1693 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
1694 $fPrevCoord = false;