<?php
+ require_once(CONST_BasePath.'/lib/PlaceLookup.php');
+
class Geocode
{
protected $oDB;
protected $aExcludePlaceIDs = array();
protected $bDeDupe = true;
- protected $bReverseInPlan = false;
+ protected $bReverseInPlan = true;
protected $iLimit = 20;
protected $iFinalLimit = 10;
$sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
$sSQL .= "group by place_id";
if (!$this->bDeDupe) $sSQL .= ",place_id ";
+ /*
$sSQL .= " union ";
$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,";
$sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
$sSQL .= "group by place_id";
if (!$this->bDeDupe) $sSQL .= ",place_id";
$sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
+ */
}
$sSQL .= " order by importance desc";
function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
{
/*
- Calculate all searches using aValidTokens i.e.
- 'Wodsworth Road, Sheffield' =>
+ Calculate all searches using aValidTokens i.e.
+ 'Wodsworth Road, Sheffield' =>
- Phrase Wordset
- 0 0 (wodsworth road)
- 0 1 (wodsworth)(road)
- 1 0 (sheffield)
+ Phrase Wordset
+ 0 0 (wodsworth road)
+ 0 1 (wodsworth)(road)
+ 1 0 (sheffield)
- Score how good the search is so they can be ordered
+ Score how good the search is so they can be ordered
*/
foreach($aPhrases as $iPhrase => $sPhrase)
{
/* Perform the actual query lookup.
Returns an ordered list of results, each with the following fields:
- osm_type: type of corresponding OSM object
+ osm_type: type of corresponding OSM object
N - node
W - way
R - relation
P - postcode (internally computed)
- osm_id: id of corresponding OSM object
- class: general object class (corresponds to tag key of primary OSM tag)
- type: subclass of object (corresponds to tag value of primary OSM tag)
- admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
- rank_search: rank in search hierarchy
+ osm_id: id of corresponding OSM object
+ class: general object class (corresponds to tag key of primary OSM tag)
+ type: subclass of object (corresponds to tag value of primary OSM tag)
+ admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
+ rank_search: rank in search hierarchy
(see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
- rank_address: rank in address hierarchy (determines orer in address)
- place_id: internal key (may differ between different instances)
- country_code: ISO country code
- langaddress: localized full address
- placename: localized name of object
- ref: content of ref tag (if available)
- lon: longitude
- lat: latitude
- importance: importance of place based on Wikipedia link count
- addressimportance: cumulated importance of address elements
- extra_place: type of place (for admin boundaries, if there is a place tag)
- aBoundingBox: bounding Box
- label: short description of the object class/type (English only)
- name: full name (currently the same as langaddress)
- foundorder: secondary ordering for places with same importance
+ rank_address: rank in address hierarchy (determines orer in address)
+ place_id: internal key (may differ between different instances)
+ country_code: ISO country code
+ langaddress: localized full address
+ placename: localized name of object
+ ref: content of ref tag (if available)
+ lon: longitude
+ lat: latitude
+ importance: importance of place based on Wikipedia link count
+ addressimportance: cumulated importance of address elements
+ extra_place: type of place (for admin boundaries, if there is a place tag)
+ aBoundingBox: bounding Box
+ label: short description of the object class/type (English only)
+ name: full name (currently the same as langaddress)
+ foundorder: secondary ordering for places with same importance
*/
function lookup()
{
{
// Start with a blank search
$aSearches = array(
- array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
- 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
- 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
+ array('iSearchRank' => 0,
+ 'iNamePhrase' => -1,
+ 'sCountryCode' => false,
+ 'aName' => array(),
+ 'aAddress' => array(),
+ 'aFullNameAddress' => array(),
+ 'aNameNonSearch' => array(),
+ 'aAddressNonSearch' => array(),
+ 'sOperator' => '',
+ 'aFeatureName' => array(),
+ 'sClass' => '',
+ 'sType' => '',
+ 'sHouseNumber' => '',
+ 'fLat' => '',
+ 'fLon' => '',
+ 'fRadius' => ''
+ )
);
// Do we have a radius search?
{
$sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
- if ($bBoundingBoxSearch)
- $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
+ if ($bBoundingBoxSearch)
+ $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
$sSQL .= " order by st_area(geometry) desc limit 1";
if (CONST_Debug) var_dump($sSQL);
$aPlaceIDs = $this->oDB->getCol($sSQL);
}
}
}
+ // If a coordinate is given, the search must either
+ // be for a name or a special search. Ignore everythin else.
+ else if ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass'])
+ {
+ $aPlaceIDs = array();
+ }
else
{
$aPlaceIDs = array();
// TODO: filter out the pointless search terms (2 letter name tokens and less)
// they might be right - but they are just too darned expensive to run
if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
- if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
+ //if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
{
// For infrequent name terms disable index usage for address
sizeof($aSearch['aName']) == 1 &&
$aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
{
- $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
+ //$aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
+ $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
}
else
{
$aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
- if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
+ //if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
}
}
if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
$aPlaceIDs = $this->oDB->getCol($sSQL);
// If not try the aux fallback table
+ /*
if (!sizeof($aPlaceIDs))
{
$sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
if (CONST_Debug) var_dump($sSQL);
$aPlaceIDs = $this->oDB->getCol($sSQL);
}
+ */
if (!sizeof($aPlaceIDs))
{
if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
}
- if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
+ if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
foreach($aSearchResults as $iResNum => $aResult)
{
// Default
- $fDiameter = 0.0001;
-
- if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
- && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
- {
- $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
- }
- elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
- && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
+ $fDiameter = getResultDiameter($aResult);
+
+ $oPlaceLookup = new PlaceLookup($this->oDB);
+ $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
+ $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
+ $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
+ $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
+ $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
+ $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
+
+ $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
+ if ($aOutlineResult)
{
- $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
+ $aResult = array_merge($aResult, $aOutlineResult);
}
- $fRadius = $fDiameter / 2;
-
- if (CONST_Search_AreaPolygons)
- {
- // Get the bounding box and outline polygon
- $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
- $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
- $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
- $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
- if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
- if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
- if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
- if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
- $sFrom = " from placex where place_id = ".$aResult['place_id'];
- if ($this->fPolygonSimplificationThreshold > 0)
- {
- $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
- }
- else
- {
- $sSQL .= $sFrom;
- }
-
- $aPointPolygon = $this->oDB->getRow($sSQL);
- if (PEAR::IsError($aPointPolygon))
- {
- failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
- }
-
- if ($aPointPolygon['place_id'])
- {
- if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
- if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
- if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
- if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
-
- if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
- {
- $aResult['lat'] = $aPointPolygon['centrelat'];
- $aResult['lon'] = $aPointPolygon['centrelon'];
- }
-
- if ($this->bIncludePolygonAsPoints)
- {
- // Translate geometry string to point array
- if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
- {
- preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
- }
- elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
- {
- preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
- }
- elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
- {
- $iSteps = max(8, min(100, ($fRadius * 40000)^2));
- $fStepSize = (2*pi())/$iSteps;
- $aPolyPoints = array();
- for($f = 0; $f < 2*pi(); $f += $fStepSize)
- {
- $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
- }
- }
- }
-
- // Output data suitable for display (points and a bounding box)
- if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
- {
- $aResult['aPolyPoints'] = array();
- foreach($aPolyPoints as $aPoint)
- {
- $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
- }
- }
-
- if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
- {
- $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
- $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
- }
- if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
- {
- $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
- $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
- }
- $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
- }
- }
-
+
if ($aResult['extra_place'] == 'city')
{
$aResult['class'] = 'place';
$aResult['rank_search'] = 16;
}
- if (!isset($aResult['aBoundingBox']))
- {
- $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
- $fStepSize = (2*pi())/$iSteps;
- $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
- $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
- $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
- $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
-
- // Output data suitable for display (points and a bounding box)
- if ($this->bIncludePolygonAsPoints)
- {
- $aPolyPoints = array();
- for($f = 0; $f < 2*pi(); $f += $fStepSize)
- {
- $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
- }
- $aResult['aPolyPoints'] = array();
- foreach($aPolyPoints as $aPoint)
- {
- $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
- }
- }
- $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
- }
-
// Is there an icon set for this type of result?
if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
&& $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])