]> git.openstreetmap.org Git - nominatim.git/blob - src/nominatim_api/v1/format_json.py
Merge pull request #3588 from lonvia/optional-reverse-api
[nominatim.git] / src / nominatim_api / v1 / format_json.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2024 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Helper functions for output of results in json formats.
9 """
10 from typing import Mapping, Any, Optional, Tuple, Union
11
12 from ..utils.json_writer import JsonWriter
13 from ..results import AddressLines, ReverseResults, SearchResults
14 from . import classtypes as cl
15
16
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])
21
22
23 def _write_typed_address(out: JsonWriter, address: Optional[AddressLines],
24                          country_code: Optional[str]) -> None:
25     parts = {}
26     for line in (address or []):
27         if line.isaddress:
28             if line.local_name:
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']
35
36     for k, v in parts.items():
37         out.keyval(k, v)
38
39     if country_code:
40         out.keyval('country_code', country_code)
41
42
43 def _write_geocodejson_address(out: JsonWriter,
44                                address: Optional[AddressLines],
45                                obj_place_id: Optional[int],
46                                country_code: Optional[str]) -> None:
47     extra = {}
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
59
60     for k, v in extra.items():
61         out.keyval(k, v)
62
63     if country_code:
64         out.keyval('country_code', country_code)
65
66
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.
71     """
72     out = JsonWriter()
73
74     if simple:
75         if not results:
76             return '{"error":"Unable to geocode"}'
77     else:
78         out.start_array()
79
80     for result in results:
81         out.start_object()\
82              .keyval_not_none('place_id', result.place_id)\
83              .keyval('licence', cl.OSM_ATTRIBUTION)\
84
85         _write_osm_id(out, result.osm_object)
86
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,
94                                                    result.rank_address,
95                                                    result.country_code))\
96            .keyval('name', result.locale_name or '')\
97            .keyval('display_name', result.display_name or '')
98
99         if options.get('icon_base_url', None):
100             icon = cl.ICONS.get(result.category)
101             if icon:
102                 out.keyval('icon', f"{options['icon_base_url']}/{icon}.p.20.png")
103
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()
108
109         if options.get('extratags', False):
110             out.keyval('extratags', result.extratags)
111
112         if options.get('namedetails', False):
113             out.keyval('namedetails', result.names)
114
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()\
121            .end_array().next()
122
123         if result.geometry:
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'))
129
130         out.end_object()
131
132         if simple:
133             return out()
134
135         out.next()
136
137     out.end_array()
138
139     return out()
140
141
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.
146     """
147     if not results and simple:
148         return '{"error":"Unable to geocode"}'
149
150     out = JsonWriter()
151
152     out.start_object()\
153        .keyval('type', 'FeatureCollection')\
154        .keyval('licence', cl.OSM_ATTRIBUTION)\
155        .key('features').start_array()
156
157     for result in results:
158         out.start_object()\
159              .keyval('type', 'Feature')\
160              .key('properties').start_object()
161
162         out.keyval_not_none('place_id', result.place_id)
163
164         _write_osm_id(out, result.osm_object)
165
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,
171                                                    result.rank_address,
172                                                    result.country_code))\
173            .keyval('name', result.locale_name or '')\
174            .keyval('display_name', result.display_name or '')
175
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()
180
181         if options.get('extratags', False):
182             out.keyval('extratags', result.extratags)
183
184         if options.get('namedetails', False):
185             out.keyval('namedetails', result.names)
186
187         out.end_object().next()  # properties
188
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()
193
194         out.key('geometry').raw(result.geometry.get('geojson')
195                                 or result.centroid.to_geojson()).next()
196
197         out.end_object().next()
198
199     out.end_array().next().end_object()
200
201     return out()
202
203
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.
207     """
208     if not results and simple:
209         return '{"error":"Unable to geocode"}'
210
211     out = JsonWriter()
212
213     out.start_object()\
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()
222
223     for result in results:
224         out.start_object()\
225              .keyval('type', 'Feature')\
226              .key('properties').start_object()\
227                                .key('geocoding').start_object()
228
229         out.keyval_not_none('place_id', result.place_id)
230
231         _write_osm_id(out, result.osm_object)
232
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)\
239
240         if options.get('addressdetails', False):
241             _write_geocodejson_address(out, result.address_rows, result.place_id,
242                                        result.country_code)
243
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()
251
252         out.end_object().next().end_object().next()
253
254         out.key('geometry').raw(result.geometry.get('geojson')
255                                 or result.centroid.to_geojson()).next()
256
257         out.end_object().next()
258
259     out.end_array().next().end_object()
260
261     return out()
262
263
264 GEOCODEJSON_RANKS = {
265     3: 'locality',
266     4: 'country',
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'}