1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2024 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Helper functions for output of results in json formats.
10 from typing import Mapping, Any, Optional, Tuple, Union
12 from ..utils.json_writer import JsonWriter
13 from ..results import AddressLines, ReverseResults, SearchResults
14 from . import classtypes as cl
17 def _write_osm_id(out: JsonWriter, osm_object: Optional[Tuple[str, int]]) -> None:
18 if osm_object is not None:
19 out.keyval_not_none('osm_type', cl.OSM_TYPE_NAME.get(osm_object[0], None))\
20 .keyval('osm_id', osm_object[1])
23 def _write_typed_address(out: JsonWriter, address: Optional[AddressLines],
24 country_code: Optional[str]) -> None:
26 for line in (address or []):
29 label = cl.get_label_tag(line.category, line.extratags,
30 line.rank_address, country_code)
31 if label not in parts:
32 parts[label] = line.local_name
33 if line.names and 'ISO3166-2' in line.names and line.admin_level:
34 parts[f"ISO3166-2-lvl{line.admin_level}"] = line.names['ISO3166-2']
36 for k, v in parts.items():
40 out.keyval('country_code', country_code)
43 def _write_geocodejson_address(out: JsonWriter,
44 address: Optional[AddressLines],
45 obj_place_id: Optional[int],
46 country_code: Optional[str]) -> None:
48 for line in (address or []):
49 if line.isaddress and line.local_name:
50 if line.category[1] in ('postcode', 'postal_code'):
51 out.keyval('postcode', line.local_name)
52 elif line.category[1] == 'house_number':
53 out.keyval('housenumber', line.local_name)
54 elif ((obj_place_id is None or obj_place_id != line.place_id)
55 and line.rank_address >= 4 and line.rank_address < 28):
56 rank_name = GEOCODEJSON_RANKS[line.rank_address]
57 if rank_name not in extra:
58 extra[rank_name] = line.local_name
60 for k, v in extra.items():
64 out.keyval('country_code', country_code)
67 def format_base_json(results: Union[ReverseResults, SearchResults],
68 options: Mapping[str, Any], simple: bool,
69 class_label: str) -> str:
70 """ Return the result list as a simple json string in custom Nominatim format.
76 return '{"error":"Unable to geocode"}'
80 for result in results:
82 .keyval_not_none('place_id', result.place_id)\
83 .keyval('licence', cl.OSM_ATTRIBUTION)\
85 _write_osm_id(out, result.osm_object)
87 out.keyval('lat', f"{result.centroid.lat}")\
88 .keyval('lon', f"{result.centroid.lon}")\
89 .keyval(class_label, result.category[0])\
90 .keyval('type', result.category[1])\
91 .keyval('place_rank', result.rank_search)\
92 .keyval('importance', result.calculated_importance())\
93 .keyval('addresstype', cl.get_label_tag(result.category, result.extratags,
95 result.country_code))\
96 .keyval('name', result.locale_name or '')\
97 .keyval('display_name', result.display_name or '')
99 if options.get('icon_base_url', None):
100 icon = cl.ICONS.get(result.category)
102 out.keyval('icon', f"{options['icon_base_url']}/{icon}.p.20.png")
104 if options.get('addressdetails', False):
105 out.key('address').start_object()
106 _write_typed_address(out, result.address_rows, result.country_code)
107 out.end_object().next()
109 if options.get('extratags', False):
110 out.keyval('extratags', result.extratags)
112 if options.get('namedetails', False):
113 out.keyval('namedetails', result.names)
115 bbox = cl.bbox_from_result(result)
116 out.key('boundingbox').start_array()\
117 .value(f"{bbox.minlat:0.7f}").next()\
118 .value(f"{bbox.maxlat:0.7f}").next()\
119 .value(f"{bbox.minlon:0.7f}").next()\
120 .value(f"{bbox.maxlon:0.7f}").next()\
124 for key in ('text', 'kml'):
125 out.keyval_not_none('geo' + key, result.geometry.get(key))
126 if 'geojson' in result.geometry:
127 out.key('geojson').raw(result.geometry['geojson']).next()
128 out.keyval_not_none('svg', result.geometry.get('svg'))
142 def format_base_geojson(results: Union[ReverseResults, SearchResults],
143 options: Mapping[str, Any],
144 simple: bool) -> str:
145 """ Return the result list as a geojson string.
147 if not results and simple:
148 return '{"error":"Unable to geocode"}'
153 .keyval('type', 'FeatureCollection')\
154 .keyval('licence', cl.OSM_ATTRIBUTION)\
155 .key('features').start_array()
157 for result in results:
159 .keyval('type', 'Feature')\
160 .key('properties').start_object()
162 out.keyval_not_none('place_id', result.place_id)
164 _write_osm_id(out, result.osm_object)
166 out.keyval('place_rank', result.rank_search)\
167 .keyval('category', result.category[0])\
168 .keyval('type', result.category[1])\
169 .keyval('importance', result.calculated_importance())\
170 .keyval('addresstype', cl.get_label_tag(result.category, result.extratags,
172 result.country_code))\
173 .keyval('name', result.locale_name or '')\
174 .keyval('display_name', result.display_name or '')
176 if options.get('addressdetails', False):
177 out.key('address').start_object()
178 _write_typed_address(out, result.address_rows, result.country_code)
179 out.end_object().next()
181 if options.get('extratags', False):
182 out.keyval('extratags', result.extratags)
184 if options.get('namedetails', False):
185 out.keyval('namedetails', result.names)
187 out.end_object().next() # properties
189 out.key('bbox').start_array()
190 for coord in cl.bbox_from_result(result).coords:
191 out.float(coord, 7).next()
192 out.end_array().next()
194 out.key('geometry').raw(result.geometry.get('geojson')
195 or result.centroid.to_geojson()).next()
197 out.end_object().next()
199 out.end_array().next().end_object()
204 def format_base_geocodejson(results: Union[ReverseResults, SearchResults],
205 options: Mapping[str, Any], simple: bool) -> str:
206 """ Return the result list as a geocodejson string.
208 if not results and simple:
209 return '{"error":"Unable to geocode"}'
214 .keyval('type', 'FeatureCollection')\
215 .key('geocoding').start_object()\
216 .keyval('version', '0.1.0')\
217 .keyval('attribution', cl.OSM_ATTRIBUTION)\
218 .keyval('licence', 'ODbL')\
219 .keyval_not_none('query', options.get('query'))\
220 .end_object().next()\
221 .key('features').start_array()
223 for result in results:
225 .keyval('type', 'Feature')\
226 .key('properties').start_object()\
227 .key('geocoding').start_object()
229 out.keyval_not_none('place_id', result.place_id)
231 _write_osm_id(out, result.osm_object)
233 out.keyval('osm_key', result.category[0])\
234 .keyval('osm_value', result.category[1])\
235 .keyval('type', GEOCODEJSON_RANKS[max(3, min(28, result.rank_address))])\
236 .keyval_not_none('accuracy', getattr(result, 'distance', None), transform=int)\
237 .keyval('label', result.display_name or '')\
238 .keyval_not_none('name', result.locale_name or None)\
240 if options.get('addressdetails', False):
241 _write_geocodejson_address(out, result.address_rows, result.place_id,
244 out.key('admin').start_object()
245 if result.address_rows:
246 for line in result.address_rows:
247 if line.isaddress and (line.admin_level or 15) < 15 and line.local_name \
248 and line.category[0] == 'boundary' and line.category[1] == 'administrative':
249 out.keyval(f"level{line.admin_level}", line.local_name)
250 out.end_object().next()
252 out.end_object().next().end_object().next()
254 out.key('geometry').raw(result.geometry.get('geojson')
255 or result.centroid.to_geojson()).next()
257 out.end_object().next()
259 out.end_array().next().end_object()
264 GEOCODEJSON_RANKS = {
267 5: 'state', 6: 'state', 7: 'state', 8: 'state', 9: 'state',
268 10: 'county', 11: 'county', 12: 'county',
269 13: 'city', 14: 'city', 15: 'city', 16: 'city',
270 17: 'district', 18: 'district', 19: 'district', 20: 'district', 21: 'district',
271 22: 'locality', 23: 'locality', 24: 'locality',
272 25: 'street', 26: 'street', 27: 'street', 28: 'house'}