Skip to content

Places

Place

Place(maps: Map, cache: Optional[BaseCache] = None)

Google Places lookup client.

Purpose

Resolves place details and text queries into canonical location records.

Attributes:

Name Type Description
maps Optional[Map]

Google Maps gateway used for Places requests.

cache Optional[BaseCache]

Optional response cache.

country Optional[str]

Current search region bias.

query Optional[str]

Current place search query.

hit Optional[Dict[str, Any]]

Most recent cache hit.

params Optional[Dict[str, str]]

Current API query parameters.

request Optional[Dict[str, str]]

Last request payload or query.

search Optional[Dict]

Most recent search response.

results Optional[List]

Most recent candidate locations.

details Optional[Dict]

Most recently retrieved place details.

geometry Optional[Dict]

Location geometry from a place response.

key Optional[str]

Cache key for the current lookup.

output Optional[Dict]

Most recent normalized location result.

prefix Optional[str]

Current cache-key namespace.

parts Optional[Tuple]

Components used to construct the current cache key.

place_id Optional[str]

Current Google Places identifier.

Purpose

Initializes Place objects given a map and optional cache

Parameters:

Name Type Description Default
maps Maps

Maps gateway instance.

required
cache Optional[BaseCache]

Optional cache for query results.

None

Returns:

Type Description
None

Places instance with text search and place-details helpers.

Source code in mapping.py
def __init__( self, maps: Map, cache: Optional[ BaseCache ] = None ) -> None:
	"""

		Purpose:
			Initializes Place objects given a map and optional cache

		Args:
			maps (Maps): Maps gateway instance.
			cache (Optional[BaseCache]): Optional cache for query results.

		Returns:
			Places instance with text search and place-details helpers.

	"""
	self.maps = maps
	self.cache = cache
	self.country = None
	self.query = None
	self.hit = None
	self.params = None
	self.request = None
	self.search = None
	self.results = None
	self.details = None
	self.geometry = None
	self.key = None
	self.output = None
	self.prefix = None
	self.parts = None
	self.place_id = None

Methods:

key_for

key_for(prefix: str, parts: List[str]) -> str | None
Purpose

Create a stable cache key from a namespace prefix and one or more string parts.

Parameters:

Name Type Description Default
prefix str

Cache namespace or operation prefix.

required
parts List[str]

Values that uniquely identify the request.

required

Returns:

Type Description
str | None

str | None: Normalized cache key.

Source code in mapping.py
def key_for( self, prefix: str, parts: List[ str ] ) -> str | None:
	"""

		Purpose:
			Create a stable cache key from a namespace prefix and one or more
			string parts.

		Args:
			prefix (str):
				Cache namespace or operation prefix.
			parts (List[str]):
				Values that uniquely identify the request.

		Returns:
			str | None:
				Normalized cache key.

	"""
	try:
		throw_if( 'prefix', prefix )
		throw_if( 'parts', parts )
		if not isinstance( prefix, str ) or not isinstance( parts, list ) or any(
				not isinstance( part, str ) for part in parts ):
			raise TypeError( 'prefix must be a string and parts a list of strings.' )
		self.prefix = prefix
		self.parts = parts
		joined = ' '.join( str( p ).strip( ) for p in parts if p and str( p ).strip( ) )
		return f'{self.prefix}::{joined}'
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Places'
		exception.method = "key_for( self, prefix: str, parts: List[ str ] ) -> str | None"
		raise exception

component_value

component_value(
    components: List[Dict[str, Any]],
    kind: str,
    want_long: bool = False,
) -> Optional[str]
Purpose

Extract a single address component value from a Google Places or Geocoding address_components collection.

Parameters:

Name Type Description Default
components List[Dict[str, Any]]

Google address component dictionaries.

required
kind str

Component type to extract, such as country or locality.

required
want_long bool

When True, return long_name instead of short_name.

False

Returns:

Type Description
Optional[str]

Optional[str]: Component value when present; otherwise None.

Source code in mapping.py
def component_value( self, components: List[ Dict[ str, Any ] ], kind: str,
	want_long: bool = False ) -> Optional[ str ]:
	"""

		Purpose:
			Extract a single address component value from a Google Places or
			Geocoding address_components collection.

		Args:
			components (List[Dict[str, Any]]): Google address component dictionaries.
			kind (str): Component type to extract, such as country or locality.
			want_long (bool): When True, return long_name instead of short_name.

		Returns:
			Optional[str]: Component value when present; otherwise None.

	"""
	try:
		throw_if( 'components', components )
		throw_if( 'kind', kind )
		for component in components or [ ]:
			if kind in (component.get( 'types' ) or [ ]):
				if want_long:
					return component.get( 'long_name' ) or None
				return component.get( 'short_name' ) or None
		return None
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Places'
		exception.method = "component_value( self, components: List[ Dict[ str, Any ] ], kind: str, want_long: bool=False ) -> Optional[ str ]"
		raise exception

flatten_place_details

flatten_place_details(
    details: Dict[str, Any], query: str = ""
) -> Dict[str, Any]
Purpose

Convert a Place Details result into the same flattened output shape used by Geocoder.flatten_geocode(...).

Parameters:

Name Type Description Default
details Dict[str, Any]

Google Place Details result dictionary.

required
query str

Original query text, when available.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Canonical location dictionary.

Source code in mapping.py
def flatten_place_details( self, details: Dict[ str, Any ], query: str = '' ) -> Dict[
	str, Any ]:
	"""

		Purpose:
			Convert a Place Details result into the same flattened output shape
			used by Geocoder.flatten_geocode(...).

		Args:
			details (Dict[str, Any]): Google Place Details result dictionary.
			query (str): Original query text, when available.

		Returns:
			Dict[str, Any]: Canonical location dictionary.

	"""
	try:
		throw_if( 'details', details )
		geometry = (details.get( 'geometry' ) or { }).get( 'location' ) or { }
		components = details.get( 'address_components', [ ] ) or [ ]
		return { 'formatted_address': details.get( 'formatted_address' ),
			'lat': geometry.get( 'lat' ), 'lng': geometry.get( 'lng' ),
			'place_id': details.get( 'place_id' ),
			'types': ','.join( details.get( 'types', [ ] ) ) if details.get( 'types' ) else None,
			'country_code': self.component_value( components, 'country' ),
			'country_name': self.component_value( components, 'country', want_long=True ),
			'admin_level_1': self.component_value( components, 'administrative_area_level_1' ),
			'admin_level_2': self.component_value( components, 'administrative_area_level_2' ),
			'locality': (
					self.component_value( components, 'locality' ) or self.component_value( components, 'postal_town' )),
			'postal_code': self.component_value( components, 'postal_code' ),
			'name': details.get( 'name' ), 'business_status': details.get( 'business_status' ),
			'rating': details.get( 'rating' ),
			'user_ratings_total': details.get( 'user_ratings_total' ),
			'website': details.get( 'website' ),
			'formatted_phone_number': details.get( 'formatted_phone_number' ),
			'source': 'places', 'query': query }
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Places'
		exception.method = "flatten_place_details( self, details: Dict[ str, Any ], query: str = '' ) -> Dict[ str, Any ]"
		raise exception

place_details

place_details(place_id: str) -> Dict[str, Any] | None
Purpose

Fetch and flatten details for a known Google place_id.

Parameters:

Name Type Description Default
place_id str

Google Places place identifier.

required

Returns:

Type Description
Dict[str, Any] | None

Dict[str, Any] | None: Canonical flattened place details.

Source code in mapping.py
def place_details( self, place_id: str ) -> Dict[ str, Any ] | None:
	"""

		Purpose:
			Fetch and flatten details for a known Google place_id.

		Args:
			place_id (str): Google Places place identifier.

		Returns:
			Dict[str, Any] | None: Canonical flattened place details.

	"""
	try:
		throw_if( 'place_id', place_id )
		self.place_id = place_id
		self.key = self.key_for( 'place_details', [ self.place_id ] )
		if self.cache:
			self.hit = self.cache.get( self.key )
			if self.hit:
				return self.hit
		fields = ('formatted_address, geometry, address_component, place_id,type,'
		          'name, business_status, rating, user_ratings_total, website,'
		          'formatted_phone_number')
		self.request = { 'place_id': self.place_id, 'fields': fields }
		self.details = self.maps.request( 'place/details/json', self.request ).get( 'result', { } )
		if not self.details:
			raise NotFound( f'No place details found for "{place_id}" ' )
		self.output = self.flatten_place_details( self.details, query=place_id )
		if self.cache:
			self.cache.set( self.key, self.output )
		return self.output
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Places'
		exception.method = "place_details( self, place_id: str ) -> Dict[ str, Any ] | None"
		raise exception

text_to_location

text_to_location(
    query: str, country: str = "US"
) -> Dict[str, Any] | None
Purpose

Resolve a free-text query into a canonical address and coordinate record via Google Places Text Search and Place Details.

Parameters:

Name Type Description Default
query str

Arbitrary human-entered text such as "Newcastle, NSW, AU".

required
country str

ISO-2 region bias such as "AU" or "US".

'US'

Returns:

Type Description
Dict[str, Any] | None

Dict[str, Any] | None: Canonical location dictionary compatible with Geocoder output.

Raises:

Type Description
NotFound

Raised when no candidate is returned.

Source code in mapping.py
def text_to_location( self, query: str, country: str = 'US' ) -> Dict[ str, Any ] | None:
	"""

		Purpose:
			Resolve a free-text query into a canonical address and coordinate
			record via Google Places Text Search and Place Details.

		Args:
			query (str):
				Arbitrary human-entered text such as "Newcastle, NSW, AU".
			country (str):
				ISO-2 region bias such as "AU" or "US".

		Returns:
			Dict[str, Any] | None:
				Canonical location dictionary compatible with Geocoder output.

		Raises:
			NotFound:
				Raised when no candidate is returned.

	"""
	try:
		throw_if( 'query', query )
		self.query = query.strip( )
		self.country = str( country or '' ).strip( )
		self.key = self.key_for( 'places', [ self.query, self.country.upper( ) ] )
		if self.cache:
			self.hit = self.cache.get( self.key )
			if self.hit:
				return self.hit
		self.params = { 'query': self.query }
		if self.country:
			self.params[ 'region' ] = self.country.upper( )
		self.search = self.maps.request( 'place/textsearch/json', self.params )
		self.results = self.search.get( 'results' ) or [ ]
		if not self.results:
			raise NotFound( f'No places match for "{self.query}" ' )
		top = self.results[ 0 ]
		place_id = top.get( 'place_id' )
		if not place_id:
			raise NotFound( 'Top place had no place_id' )
		fields = ('formatted_address,geometry,address_component,place_id,type,'
		          'name,business_status,rating,user_ratings_total,website,'
		          'formatted_phone_number')
		_payload = { 'place_id': place_id, 'fields': fields }
		self.request = _payload
		self.details = self.maps.request( 'place/details/json', self.request ).get( 'result', { } )
		if not self.details:
			raise NotFound( f'No place details found for "{self.query}" ' )
		self.output = self.flatten_place_details( self.details, query=self.query )
		if self.cache:
			self.cache.set( self.key, self.output )
		return self.output
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Places'
		exception.method = "text_to_location( self, **args ) -> Dict[ str, Any ] | None"
		raise exception

search_candidates

search_candidates(
    query: str, country: str = "US", lmt: int = 5
) -> List[Dict[str, Any]]
Purpose

Return multiple Places Text Search candidates for a query. This is intended for future UI candidate-selection workflows.

Parameters:

Name Type Description Default
query str

Free-text search query.

required
country str

ISO-2 region bias.

'US'
lmt int

Maximum candidates to return.

5

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Raw candidate dictionaries returned by Text Search.

Source code in mapping.py
def search_candidates( self, query: str, country: str = 'US', lmt: int = 5 ) -> List[
	Dict[ str, Any ] ]:
	"""

		Purpose:
			Return multiple Places Text Search candidates for a query. This is
			intended for future UI candidate-selection workflows.

		Args:
			query (str): Free-text search query.
			country (str): ISO-2 region bias.
			lmt (int): Maximum candidates to return.

		Returns:
			List[Dict[str, Any]]: Raw candidate dictionaries returned by Text Search.

	"""
	try:
		throw_if( 'query', query )
		self.query = query.strip( )
		self.country = str( country or '' ).strip( )
		self.params = { 'query': self.query }
		if self.country:
			self.params[ 'region' ] = self.country.upper( )
		self.search = self.maps.request( 'place/textsearch/json', self.params )
		self.results = self.search.get( 'results' ) or [ ]
		if not self.results:
			raise NotFound( f'No places match for "{self.query}" ' )
		return self.results[ :max( 1, int( lmt ) ) ]
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Places'
		exception.method = "search_candidates( self, **args ) -> List[ Dict[ str, Any ] ]"
		raise exception