1 import { last_api_request_url_store, error_store } from './stores.js';
3 function api_request_progress(status) {
4 var loading_el = document.getElementById('loading');
5 if (!loading_el) return; // might not be on page yet
7 loading_el.style.display = (status === 'start') ? 'block' : null;
10 export async function fetch_from_api(endpoint_name, params, callback) {
11 var api_url = generate_nominatim_api_url(endpoint_name, params);
13 api_request_progress('start');
14 if (endpoint_name !== 'status') last_api_request_url_store.set(null);
17 await fetch(api_url, { headers: Nominatim_Config.Nominatim_API_Endpoint_Headers || {} })
18 .then(response => response.json())
21 error_store.set(data.error.message);
24 api_request_progress('finish');
27 error_store.set(`Error fetching data from ${api_url} (${error})`);
28 api_request_progress('finish');
31 if (endpoint_name !== 'status') last_api_request_url_store.set(api_url);
34 var fetch_content_cache = {};
35 export async function fetch_content_into_element(url, dom_element) {
36 if (!window.location.protocol.match(/^http/)) {
37 dom_element.innerHTML = `Cannot display data from ${url} here. `
38 + 'Browser security prevents loading content from file:// URLs.';
42 if (fetch_content_cache[url]) {
43 dom_element.innerHTML = fetch_content_cache[url];
48 .then(response => response.text())
50 html = html.replace('Nominatim_API_Endpoint', Nominatim_Config.Nominatim_API_Endpoint);
51 dom_element.innerHTML = html;
52 fetch_content_cache[url] = html;
55 dom_element.innerHTML = `Error fetching content from ${url} (${error})`;
59 function generate_nominatim_api_url(endpoint_name, params) {
60 extend_parameters(params, Nominatim_Config.Nominatim_API_Endpoint_Params);
61 return Nominatim_Config.Nominatim_API_Endpoint + endpoint_name + '.php?'
62 + Object.keys(clean_up_parameters(params)).map((k) => {
63 return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
67 function extend_parameters(params, params2) {
68 var param_names = Object.keys(params2);
69 for (var i = 0; i < param_names.length; i += 1) {
70 params[param_names[i]] = params2[param_names[i]];
74 function clean_up_parameters(params) {
75 // `&a=&b=&c=1` => '&c=1'
76 var param_names = Object.keys(params);
77 for (var i = 0; i < param_names.length; i += 1) {
78 var val = params[param_names[i]];
79 if (typeof (val) === 'undefined' || val === '' || val === null) {
80 delete params[param_names[i]];
86 export function update_html_title(title) {
87 document.title = [title, Nominatim_Config.Page_Title]
88 .filter((val) => val && val.length > 1)